<template>
  <div class="salesOrderForm">
    <FixedOperation>
      <div class="flex items-center justify-between">
        <div class="leading-30px">
          <div class="inline-block">
            <svg-icon
              :icon-class="'svg_salesorder'"
              class="w-30px h-30px align-middle"
            />
            <span
              class="text-#000 leading-30px ml-10px text-16px font-bold align-bottom"
              >销售订单审批</span
            >
          </div>
          <div
            class="inline-block text-15px ml-10px"
            style="vertical-align: bottom"
            v-if="bpmnStatus"
          >
            <i
              :class="
                bpmnStatus == '审批通过'
                  ? 'h-8px w-8px bg-#fe9400 inline-block rounded'
                  : bpmnStatus == '流程未发起'
                  ? 'h-8px w-8px bg-#ccc inline-block rounded'
                  : 'h-8px w-8px bg-#10d070 inline-block rounded'
              "
            ></i>
            {{ bpmnStatus }}
          </div>
        </div>
        <div class="text-right">
          <slot></slot>
          <el-button
            type="primary"
            plain
            @click="handleSubmit('examine')"
            v-if="isExamine && isCanStart"
            >发起申请</el-button
          >
          <el-button
            type="primary"
            @click="handleSubmit('save')"
            v-if="!formDisabled"
            >保存</el-button
          >
          <el-button
            type="primary"
            plain
            v-if="formData.id"
            :disabled="
              !(
                (bpmnStatus === '商务审批' || formData.status === '5') &&
                formData.contractOrderNumber
              )
            "
            @click="handleSalesSlip"
            >签购单</el-button
          >
          <!-- <el-button @click="handleReset(form)" v-if="isCanStart"
            >重置</el-button
          > -->
          <el-button type="primary" plain @click="handleReturn">返回</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="app-container form-box">
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="130px"
        :disabled="formDisabled"
      >
        <el-collapse v-model="activeNames">
          <!-- 订单主体
            v-if="props.hidenDome.indexOf('1') == -1" -->
          <el-collapse-item
            name="订单主体"
            v-if="hidenDome.indexOf('订单主体') == -1"
          >
            <template #title>
              <TitleName
                title="订单主体"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="8">
                <el-form-item
                  label="客户名称"
                  prop="customerName"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <!-- <el-input
                    v-model="formData.customerName"
                    placeholder="请选择客户名称"
                    clearable
                    style="width: 100%"
                    @clear="
                      () => {
                        formData.customerName = ''
                        formData.customerId = ''
                      }
                    "
                  >
                    <template #append
                      ><el-button
                        icon="Search"
                        @click="selectCustomerFn('customerId')"
                    /></template>
                  </el-input> -->
                  <el-input
                    v-model="formData.customerName"
                    placeholder="请选择客户名称"
                    clearable
                    :disabled="fieldDisabled.includes('客户名称')"
                    style="width: 100%"
                    @focus="selectCustomerFn('customerId')"
                    @clear="
                      () => {
                        formData.customerName = ''
                        formData.customerId = ''
                      }
                    "
                  >
                  </el-input>
                  <!-- <el-select
                    class="w-full"
                    v-model="formData.customerId"
                    placeholder="请选择客户名称"
                    @focus="selectCustomerFn('customerId')"
                  >
                    <el-option
                      v-for="item in customerOption['customerId']"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    ></el-option>
                  </el-select> -->
                  <!-- <el-select
                    v-model="formData.customerId"
                    placeholder="请选择客户名称"
                    class="w-full"
                    filterable
                    remote
                    clearable
                    @change="changeCustomer"
                    :remote-method="queryCustomer"
                    :loading="loadingSelect"
                    no-data-text="未查询到客户"
                  >
                    <el-option
                      v-for="item in parentOptions"
                      :key="item.id"
                      :label="item.customerName"
                      :value="item.id"
                    >
                      <div>
                        <span>{{ item.customerName }}</span>
                        <span>({{ item.mainContactName }})</span>
                      </div>
                    </el-option>
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="8" v-show="formData.customerId">
                <el-form-item
                  :label="
                    formData.customerType == 'customer'
                      ? '客户社会信用代码'
                      : '身份证'
                  "
                  prop="customerCreditCode"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    :disabled="
                      fieldDisabled.includes('客户社会信用代码') ||
                      fieldDisabled.includes('身份证')
                    "
                    v-model="formData.customerCreditCode"
                    placeholder="根据“客户名称”的选择自动带出"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-show="formData.customerId">
                <el-form-item
                  label="联系人"
                  prop="cusLinkId"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-select
                    :disabled="fieldDisabled.includes('联系人')"
                    v-model="formData.cusLinkId"
                    placeholder="请选择客户联系人"
                    class="w-3/6 pr-1"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    clearable
                    filterable
                    :allow-create="false"
                    default-first-option
                    remote
                    :remote-method="
                      val => queryContactsLimitEnt(val, formData.customerId)
                    "
                    @change="changeLinkName"
                    :loading="loadingSelect"
                    no-data-text="未查询到客户联系人"
                  >
                    <el-option
                      v-for="item in contactsOptionsLimitEnt"
                      :key="item.id"
                      :label="item.contactName"
                      :value="item.id"
                    >
                      <div>
                        <span>{{ item.contactName }}</span>
                        <span v-if="item.contactNumber"
                          >({{ item.contactNumber }})</span
                        >
                      </div>
                    </el-option>
                  </el-select>
                  <el-input
                    :disabled="fieldDisabled.includes('联系人')"
                    style="width: 50%"
                    v-model="formData.linkPhone"
                    placeholder="填写联系方式"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
                <el-form-item
                  label="联系方式"
                  prop="linkPhone"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    v-model="formData.linkPhone"
                    placeholder="填写联系人手机、电话、邮箱"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="8">
                <el-form-item
                  label="销售人员"
                  prop="_transactionId"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('销售人员')"
                    v-model="formData._transactionId"
                    placeholder="请选择销售人员"
                    @focus="selectUserFn('transactionId')"
                  >
                    <el-option
                      v-for="item in userOption['transactionId']"
                      :key="item.uuid"
                      :label="item.label"
                      :value="item.uuid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="销售单位(开票单位)/部门"
                  prop="transactionDept"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <div class="w-3/6 pr-1">
                    <!-- ||
                        userStore.userInfo.orgId != 484 -->
                    <el-tree-select
                      class="w-full"
                      :disabled="
                        fieldDisabled.includes('销售单位(开票单位)/部门')
                      "
                      v-model="formData.deptId"
                      placeholder="请选择所属公司"
                      default-expand-all
                      :data="companyNoPrivOption"
                      @change="changeDept"
                      @focus="focusDept"
                      :props="{
                        value: 'id',
                        label: 'label',
                        children: 'children'
                      }"
                    />
                  </div>
                  <div class="w-3/6">
                    <el-tree-select
                      class="w-full"
                      :disabled="
                        fieldDisabled.includes('销售单位(开票单位)/部门')
                      "
                      v-model="formData.transactionDept"
                      placeholder="请选择销售部门"
                      :data="departmentNoPrivOption"
                      :props="{
                        value: 'id',
                        label: 'label',
                        children: 'children'
                      }"
                    />
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="单据日期"
                  prop="receiptsDate"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-date-picker
                    style="width: 100%"
                    :disabled="fieldDisabled.includes('单据日期')"
                    v-model="formData.receiptsDate"
                    type="date"
                    placeholder="单据日期"
                    value-format="YYYY-MM-DD"
                    @change="val => setTitle()"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="订单统计归属单位"
                  prop="sourceOrgId"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-tree-select
                    class="w-full"
                    v-model="formData.sourceOrgId"
                    placeholder="请选择订单统计归属单位"
                    :disabled="fieldDisabled.includes('订单统计归属单位')"
                    default-expand-all
                    :data="companyNoPrivOption"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 基本信息
            v-if="props.hidenDome.indexOf('1') == -1" -->
          <el-collapse-item
            name="基本信息"
            v-if="hidenDome.indexOf('基本信息') == -1"
          >
            <template #title>
              <TitleName
                title="基本信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="8">
                <el-form-item
                  label="订单标题"
                  prop="title"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    :disabled="fieldDisabled.includes('订单标题')"
                    v-model="formData.title"
                    placeholder="请输入订单标题"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="业务类型"
                  prop="bizType"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('业务类型')"
                    v-model="formData.bizType"
                    placeholder="请选择业务类型"
                  >
                    <el-option
                      v-for="item in order_biz_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                :span="formData.property == '0' ? 8 : 4"
                style="padding-right: 0"
              >
                <el-form-item
                  label="订单属性"
                  prop="property"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-radio-group
                    v-model="formData.property"
                    :disabled="fieldDisabled.includes('订单属性')"
                  >
                    <el-radio
                      v-for="item in order_property"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col
                :span="4"
                v-if="formData.property == '1'"
                style="padding-left: 5px"
              >
                <el-form-item
                  label-width="100%"
                  label="关联订单"
                  style="flex-direction: column"
                  prop="oppositeName"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    v-model="formData.oppositeName"
                    :disabled="fieldDisabled.includes('关联订单')"
                    placeholder="请选择关联订单"
                    clearable
                    type="textarea"
                    autosize
                    style="width: 100%"
                    @focus="activeOrdDialog"
                    @clear="
                      () => {
                        formData.oppositeName = ''
                        formData.oppositeId = ''
                        formData.correspondingInvoiceNumber = ''
                      }
                    "
                  >
                  </el-input>
                  <!-- <el-select
                    v-model="formData.oppositeId"
                    placeholder="请输入订单名称"
                    @focus="activeOrdDialog"
                    clearable
                  >
                    <el-option
                      v-for="item in optionsOrder"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="formData.property == '1'">
                <el-form-item
                  label-width="100%"
                  label="关联发票"
                  style="flex-direction: column"
                  prop="correspondingInvoiceNumber"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    v-model="formData.correspondingInvoiceNumber"
                    :disabled="fieldDisabled.includes('关联订单')"
                    placeholder="请选择关联发票"
                    clearable
                    style="width: 100%"
                    @focus="reversalOrder"
                    @clear="
                      () => {
                        formData.correspondingInvoiceNumber = ''
                      }
                    "
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="formData.property == '1'">
                <el-form-item
                  label="冲红原因"
                  prop="flushRedReason"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    :disabled="fieldDisabled.includes('冲红原因')"
                    v-model="formData.flushRedReason"
                    placeholder="请输入冲红原因"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
                <el-form-item
                  label="订单编号"
                  prop="number"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    :disabled="fieldDisabled.includes('订单编号')"
                    v-model="formData.number"
                    placeholder="请输入订单编号"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="8">
                <el-form-item
                  label="所属业务分类"
                  prop="businessType"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-tree-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('所属业务分类')"
                    v-model="formData.businessType"
                    @change="changeBusinessType"
                    placeholder="请选择业务分类"
                    :data="userBusinessTypeOption"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="产品属性"
                  prop="proProperty"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-select
                    disabled
                    class="w-8/24 pr-1"
                    v-model="formData.proProperty"
                    @change="changeProProperty"
                    placeholder="添加产品自动带入"
                  >
                    <el-option
                      v-for="item in product_property"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <!-- <el-radio-group
                    v-model="formData.proProperty"
                    @change="changeProProperty"
                    class="w-8/24"
                  >
                    <el-radio
                      v-for="item in product_property"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group> -->
                  <!-- ="fieldDisabled.includes('产品属性')" -->
                  <el-select
                    disabled
                    class="w-8/24 pr-1"
                    v-model="formData.proType"
                    placeholder="产品类型"
                  >
                    <el-option
                      v-for="item in order_pro_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <el-select
                    class="w-8/24"
                    disabled
                    v-model="formData.processKey"
                    placeholder="业务流程"
                  >
                    <el-option
                      v-for="item in order_process"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
                <el-form-item
                  label="业务流程"
                  prop="processKey"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-select
                    class="w-full"
                    disabled
                    v-model="formData.processKey"
                    placeholder="请选择业务流程"
                  >
                    <el-option
                      v-for="item in order_process"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="8" v-if="false">
                <el-form-item
                  label="订单金额"
                  prop="price"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    v-model="formData.price"
                    :disabled="fieldDisabled.includes('订单金额')"
                    placeholder="请填写订单金额"
                    ><template v-slot:append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
                v-if="
                  !(
                    formData.productInfoList &&
                    formData.productInfoList.some(
                      item => item.number == 'H00030000000189_7501'
                    )
                  )
                "
              >
                <el-form-item
                  label="关联合同"
                  prop="contractNames"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    @click="activeDialog"
                    :disabled="fieldDisabled.includes('关联合同')"
                    placeholder="请选择关联合同"
                    v-model="formData.contractNames"
                    clearable
                    @clear="clearAll"
                  ></el-input>
                  <!-- <el-select
                    v-model="formData.contractIds"
                    placeholder="请输入合同名称检索合同"
                    class="w-full"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    filterable
                    remote
                    multiple
                    clearable
                    :remote-method="
                      val => queryContractLimitEnt(val, formData.customerId)
                    "
                    :loading="loadingSelect"
                    no-data-text="未查询到合同"
                  >
                    <el-option
                      v-for="item in contractOptionsLimitEnt"
                      :key="item.rcId"
                      :label="item.contractName"
                      :value="item.rcId"
                    >
                      <div>
                        <span>{{ item.contractName }}</span>
                      </div>
                    </el-option>
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="关联项目"
                  prop="projectName"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    @click="selectPro"
                    :disabled="fieldDisabled.includes('关联项目')"
                    placeholder="请选择关联项目"
                    v-model="formData.projectName"
                    clearable
                    :suffix-icon="'el-icon-search'"
                    @clear="clearPro"
                  ></el-input>
                  <!-- <el-select
                    v-model="formData.projectId"
                    placeholder="请输入项目名称检索项目"
                    class="w-full"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    filterable
                    remote
                    clearable
                    :remote-method="
                      val => queryProjectLimitEnt(val, formData.customerId)
                    "
                    :loading="loadingSelect"
                    no-data-text="未查询到项目"
                  >
                    <el-option
                      v-for="item in projectOptionsLimitEnt"
                      :key="item.projectId"
                      :label="item.proName"
                      :value="item.projectId"
                    >
                      <div>
                        <span>{{ item.proName }}</span>
                      </div>
                    </el-option>
                  </el-select> -->
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
                v-if="fieldHidden.indexOf('合同(订单)编号') == -1"
              >
                <el-form-item
                  label="合同(订单)编号"
                  prop="contractOrderNumber"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    clearable
                    :disabled="
                      fieldDisabled.indexOf('合同(订单)编号') == -1
                        ? false
                        : true
                    "
                    v-model="formData.contractOrderNumber"
                    placeholder="请输入合同(订单)编号"
                  >
                    <template #append>
                      <el-button
                        :disabled="
                          fieldDisabled.indexOf('合同(订单)编号') == -1
                            ? false
                            : true
                        "
                        @click="getNumber"
                        >编号</el-button
                      >
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
                <el-form-item
                  label=" 仓库"
                  prop="warehouse"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-select
                    v-model="formData.warehouse"
                    placeholder="请输入仓库名称检索仓库"
                    class="w-full"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    filterable
                    remote
                    :remote-method="
                      val => queryWhsLimitEnt(val, { unit: formData.deptId })
                    "
                    :loading="loadingSelect"
                    no-data-text="未查询到仓库"
                  >
                    <el-option
                      v-for="item in whsOptLimitEnt"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col> -->
            </el-row>
          </el-collapse-item>
          <!-- 产品信息 -->
          <el-collapse-item
            name="产品信息"
            v-if="hidenDome.indexOf('产品信息') == -1"
          >
            <template #title>
              <TitleName
                title="产品信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <avue-crud
              ref="crudProduct"
              :disabled="formDisabled || fieldDisabled.includes('产品信息')"
              :option="crudOptionProduct"
              :data="formData.productInfoList"
              class="hide-required-asterisk"
            >
              <template #menu-left>
                <el-button
                  type="primary"
                  icon="Plus"
                  @click="addProduct"
                  :disabled="formDisabled || fieldDisabled.includes('产品信息')"
                  >添加产品</el-button
                >
              </template>
              <template #membershipLevel-form="{ row }">
                <el-input
                  v-model="row.membershipLevel"
                  placeholder="会员权益"
                  @focus="openVIP(row, '诺账通')"
                >
                </el-input>
              </template>
              <template #warehouse-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #actualPrice-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #discount-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #num-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #serviceDateArr-header="{ column }">
                <!-- <span class="text-red pr-2">*</span> -->
                <span>{{ column.label }}</span>
              </template>
              <template #warehouse-form="{ row }">
                <el-select
                  v-model="row.warehouse"
                  :disabled="formDisabled || fieldDisabled.includes('产品信息')"
                  placeholder="请输入仓库名称检索仓库"
                  class="w-full"
                  suffix-icon="Search"
                  remote-show-suffix
                  :suffix-transition="false"
                  filterable
                  remote
                  @change="val => changeWhs(val, row)"
                  :remote-method="
                    val => queryWhsLimitEnt(val, { unit: formData.deptId })
                  "
                  :loading="loadingSelect"
                  no-data-text="未查询到仓库"
                >
                  <el-option
                    v-for="item in whsOptLimitEnt"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
              <template #serviceDateArr-form="{ row }">
                <!-- || fieldDisabled.includes('产品信息') -->
                <DatePickerRange
                  v-model="row.serviceDateArr"
                  :disabled="formDisabled"
                  range-separator="-"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :clearable="false"
                  startPlaceholder="服务开始时间"
                  endPlaceholder="服务结束时间"
                />
              </template>
              <template #menu="{ row, index }">
                <el-button
                  :disabled="formDisabled || fieldDisabled.includes('产品信息')"
                  plain
                  icon="Delete"
                  link
                  @click="delRowProduct(row, index)"
                  >删除</el-button
                >
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
              <template #footer>
                <el-row
                  class="bg-#f8f8f9 border-solid border-1 border-#ebeef5 pr-5"
                >
                  <el-col :span="24" class="py-2 text-right">
                    产品记录数：<span class="text-blue-500"
                      >{{ countCrudData.num }}条</span
                    >
                    产品总数：<span class="text-blue-500">{{
                      countCrudData.total
                    }}</span
                    >个 产品总售价：<span class="text-blue-500"
                      >{{ countCrudData.totalDiscountPrice }}元</span
                    >
                    <!-- 整单折扣：<span class="text-blue-500"
                      >{{ countCrudData.discount }}%</span
                    > -->
                    产品总金额：
                    <span class="text-blue-500"
                      >{{ countCrudData.totalPrice }}元</span
                    >
                  </el-col></el-row
                >
                <el-button
                  plain
                  type="primary"
                  icon="Plus"
                  class="w-full"
                  @click="addProduct"
                  :disabled="formDisabled || fieldDisabled.includes('产品信息')"
                  >添加产品</el-button
                >
              </template>
            </avue-crud>
          </el-collapse-item>
          <!-- 代账信息-->
          <el-collapse-item
            name="代账信息"
            v-if="
              formData.productInfoList &&
              formData.productInfoList.some(
                item => item.number == 'H00030000000189_7501'
              )
            "
          >
            <!-- v-if="formData.businessType.indexOf('代理记账') != '-1'" -->
            <template #title>
              <TitleName
                title="代账信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="4">
                <el-form-item
                  label="代账业务分类"
                  prop="keepAccountType"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('代账业务分类')"
                    v-model="formData.keepAccountType"
                    placeholder="请选择代账业务分类"
                  >
                    <el-option
                      v-for="item in keep_account_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item
                  label="合同金额"
                  prop="contractSum"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    v-model="formData.contractSum"
                    :disabled="fieldDisabled.includes('合同金额')"
                    placeholder="请填写合同金额"
                    ><template v-slot:append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="合同时间起"
                  prop="contractTimeBegin"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-date-picker
                    style="width: 100%"
                    :disabled="fieldDisabled.includes('合同时间起')"
                    v-model="formData.contractTimeBegin"
                    type="date"
                    placeholder="合同时间起"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="合同时间止"
                  prop="contractTimeEnd"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-date-picker
                    style="width: 100%"
                    :disabled="fieldDisabled.includes('合同时间止')"
                    v-model="formData.contractTimeEnd"
                    type="date"
                    placeholder="合同时间止"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="关联合同"
                  prop="contractNames"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    @click="activeDialog"
                    :disabled="fieldDisabled.includes('关联合同')"
                    placeholder="请选择关联合同"
                    v-model="formData.contractNames"
                    clearable
                    @clear="clearAll"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="服务内容"
                  prop="keepAccountContentArr"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-checkbox-group
                    class="w-full"
                    :disabled="fieldDisabled.includes('服务内容')"
                    v-model="formData.keepAccountContentArr"
                    placeholder="请选择服务内容"
                  >
                    <el-checkbox
                      v-for="item in keep_account_content"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
              <el-col
                :span="8"
                v-if="formData.keepAccountContentArr?.indexOf('其他服务') != -1"
              >
                <el-form-item
                  label="其他服务"
                  prop="keepAccountOtherService"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    v-model="formData.keepAccountOtherService"
                    :disabled="fieldDisabled.includes('其他服务')"
                    placeholder="请填写其他服务"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="备注"
                  prop="keepAccountRemark"
                  style="flex-direction: column"
                  label-width="100%"
                >
                  <template #label="{ label }">
                    <div class="w-full">{{ label }}</div>
                  </template>
                  <el-input
                    v-model="formData.keepAccountRemark"
                    :disabled="fieldDisabled.includes('备注')"
                    placeholder="请填写备注"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 培训产业 -->
          <el-collapse-item
            :name="industry[formData.businessType].name"
            v-if="showTrainingIndustry && industry[formData.businessType]"
          >
            <template #title>
              <TitleName
                :title="industry[formData.businessType].name"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <avue-crud
              :ref="industry[formData.businessType].field"
              :disabled="formDisabled || fieldDisabled.includes('培训产业')"
              :option="
                crudOptionBusiness[
                  `${industry[formData.businessType].field}Option`
                ]
              "
              :data="formData[`${industry[formData.businessType].field}List`]"
              class="hide-required-asterisk"
            >
              <template #menu-left>
                <div class="flex">
                  <el-button
                    type="primary"
                    icon="Plus"
                    @click="addEducation"
                    :disabled="
                      formDisabled || fieldDisabled.includes('培训产业')
                    "
                    >添加</el-button
                  >
                  <!-- :limit="3" -->
                  <el-upload
                    v-loading="uploadLoading"
                    class="upload-demo pl-2"
                    action="#"
                    :before-upload="beforeAvatarUpload"
                    :http-request="requestFile"
                    accept=" .xls, .xlsx"
                    :show-file-list="false"
                  >
                    <el-button
                      type="primary"
                      style="font-size: 14px"
                      :disabled="
                        formDisabled || fieldDisabled.includes('培训产业')
                      "
                      ><el-icon><Upload /></el-icon>导入</el-button
                    >
                    <!-- <template #tip>
                    <div class="el-upload__tip float-right">
                      支持格式.doc .docx .pdf ，单个文件不能超过200MB
                    </div>
                  </template> -->
                  </el-upload>
                  <el-link type="primary" class="ml-5" @click="downUrl()"
                    >下载模板</el-link
                  >
                </div>
              </template>
              <template #contactName-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #idNumber-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #contactNumber-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #libraryStatus-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #library-header="{ column }">
                <span class="text-red pr-2">*</span
                ><span>{{ column.label }}</span>
              </template>
              <template #contactName-form="{ row }">
                <el-input
                  v-model="row.contactName"
                  placeholder="客户名称"
                  :disabled="formDisabled || fieldDisabled.includes('培训产业')"
                >
                  <template #append
                    ><el-button
                      icon="Search"
                      :disabled="
                        formDisabled || fieldDisabled.includes('培训产业')
                      "
                      @click="selectCustomerFn('education', row)"
                  /></template>
                </el-input>
              </template>
              <template #membershipLevel-form="{ row }">
                <el-input
                  v-model="row.membershipLevel"
                  placeholder="会员等级"
                  @focus="openVIP(row)"
                >
                </el-input>
              </template>
              <template #menu="{ row, index }">
                <el-button
                  :disabled="formDisabled || fieldDisabled.includes('培训产业')"
                  plain
                  icon="Delete"
                  link
                  @click="delEducation(row, index)"
                  >删除</el-button
                >
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
            </avue-crud>
          </el-collapse-item>
          <!-- 物流信息 -->
          <el-collapse-item
            name="物流信息"
            v-if="hidenDome.indexOf('物流信息') == -1"
          >
            <template #title>
              <TitleName
                title="物流信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="12">
                <el-form-item label="运输方式" prop="transportType">
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('运输方式')"
                    v-model="formData.transportType"
                    placeholder="请选择运输方式"
                  >
                    <el-option
                      v-for="item in order_transport_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交货日期" prop="deliveryDate">
                  <el-date-picker
                    style="width: 100%"
                    :disabled="fieldDisabled.includes('交货日期')"
                    v-model="formData.deliveryDate"
                    type="date"
                    placeholder="交货日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="运费承担" prop="transportMan">
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('运费承担')"
                    v-model="formData.transportMan"
                    placeholder="请选择运费承担"
                  >
                    <el-option
                      v-for="item in order_transport_man"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交货地点" prop="transportPlace">
                  <el-input
                    v-model="formData.transportPlace"
                    :disabled="fieldDisabled.includes('交货地点')"
                    placeholder="请输入交货地点"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 收货信息 -->
          <el-collapse-item
            name="收货信息"
            v-if="hidenDome.indexOf('收货信息') == -1"
          >
            <template #title>
              <TitleName
                title="收货信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="12">
                <el-form-item label="收货单位" prop="receiveDept">
                  <el-select
                    v-model="formData.receiveDept"
                    placeholder="请选择收货单位"
                    class="w-full"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    :disabled="fieldDisabled.includes('收货单位')"
                    filterable
                    remote
                    clearable
                    :remote-method="queryCustomer"
                    @change="changeReceiveDept"
                    :loading="loadingSelect"
                    no-data-text="未查询到收货单位"
                  >
                    <el-option
                      v-for="item in parentOptions"
                      :key="item.id"
                      :label="item.customerName"
                      :value="item.id"
                    >
                      <div>
                        <span>{{ item.customerName }}</span>
                        <span v-if="item.mainContactName"
                          >({{ item.mainContactName }})</span
                        >
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收货人" prop="receiveId">
                  <el-select
                    v-model="formData.receiveId"
                    :disabled="fieldDisabled.includes('收货人')"
                    placeholder="请选择收货人"
                    class="w-full"
                    suffix-icon="Search"
                    remote-show-suffix
                    :suffix-transition="false"
                    clearable
                    filterable
                    default-first-option
                    :reserve-keyword="false"
                    remote
                    :remote-method="
                      val =>
                        queryContactsLimitEnt(
                          val,
                          formData.receiveDept,
                          '请先选择收货单位'
                        )
                    "
                    @change="changeReceive"
                    :loading="loadingSelect"
                    no-data-text="未查询到收货人"
                  >
                    <el-option
                      v-for="item in contactsOptionsLimitEnt"
                      :key="item.id"
                      :label="item.contactName"
                      :value="item.id"
                    >
                      <div>
                        <span>{{ item.contactName }}</span>
                        <span>({{ item.contactNumber }})</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收货电话" prop="receivePhone">
                  <el-input
                    v-model="formData.receivePhone"
                    :disabled="fieldDisabled.includes('收货电话')"
                    placeholder="请输入收货电话"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收货地址" prop="receivePlace">
                  <el-input
                    v-model="formData.receivePlace"
                    :disabled="fieldDisabled.includes('收货地址')"
                    placeholder="请输入收货地址"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 销售信息 -->
          <el-collapse-item
            name="销售信息"
            v-if="hidenDome.indexOf('销售信息') == -1"
          >
            <template #title>
              <TitleName
                title="销售信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="12">
                <el-form-item label="签约时间" prop="signDate">
                  <el-date-picker
                    style="width: 100%"
                    v-model="formData.signDate"
                    :disabled="fieldDisabled.includes('签约时间')"
                    type="date"
                    placeholder="签约时间"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="销售分组" prop="sellGroup">
                  <el-select
                    class="w-full"
                    v-model="formData.sellGroup"
                    :disabled="fieldDisabled.includes('销售分组')"
                    placeholder="请选择销售分组"
                  >
                    <el-option
                      v-for="item in order_sell_group"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="签约地点" prop="signPlace">
                  <el-input
                    v-model="formData.signPlace"
                    :disabled="fieldDisabled.includes('签约地点')"
                    placeholder="请输入签约地点"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经办部门" prop="handleDept">
                  <el-tree-select
                    class="w-full"
                    v-model="formData.handleDept"
                    :disabled="fieldDisabled.includes('经办部门')"
                    placeholder="请选择经办部门"
                    :data="departmentNoPrivOption"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经办人" prop="_handleId">
                  <el-select
                    class="w-full"
                    v-model="formData._handleId"
                    :disabled="fieldDisabled.includes('经办人')"
                    placeholder="请选择经办人"
                    @focus="selectUserFn('handleId')"
                  >
                    <el-option
                      v-for="item in userOption['handleId']"
                      :key="item.uuid"
                      :label="item.label"
                      :value="item.uuid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纳税区分" prop="taxZone">
                  <el-input
                    v-model="formData.taxZone"
                    placeholder="纳税区分"
                    :disabled="fieldDisabled.includes('纳税区分')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="代理机构" prop="agencyDept">
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('代理机构')"
                    v-model="formData.agencyDept"
                    placeholder="请选择代理机构"
                  >
                    <el-option
                      v-for="item in order_agency_dept"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 收款信息 -->
          <el-collapse-item
            name="收款信息"
            v-if="hidenDome.indexOf('收款信息') == -1"
          >
            <template #title>
              <TitleName
                title="收款信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="12">
                <el-form-item label="是否需现结" prop="isNeedCash">
                  <el-radio-group
                    v-model="formData.isNeedCash"
                    :disabled="fieldDisabled.includes('是否需现结')"
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商城是否已收款" prop="isCollectMoney">
                  <el-radio-group
                    v-model="formData.isCollectMoney"
                    :disabled="fieldDisabled.includes('商城是否已收款')"
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否已现结" prop="isClash">
                  <el-radio-group
                    v-model="formData.isClash"
                    :disabled="fieldDisabled.includes('是否已现结')"
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="违约赔偿率" prop="indemnityPercent">
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('违约赔偿率')"
                    v-model="formData.indemnityPercent"
                    placeholder="请选择违约赔偿率"
                  >
                    <el-option
                      v-for="item in order_indemnity_percent"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <avue-crud
                  ref="crudRepayment"
                  :disabled="formDisabled || fieldDisabled.includes('回款明细')"
                  :option="crudOptionRepayment"
                  :data="formData.repaymentPlanList"
                  class="hide-required-asterisk"
                >
                  <template #menu-left>
                    <el-button
                      type="primary"
                      icon="Plus"
                      class="w-full"
                      :disabled="
                        formDisabled || fieldDisabled.includes('回款明细')
                      "
                      @click="addRowRepayment"
                      >添加期次</el-button
                    ></template
                  >
                  <template #repaymentPlanDate-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #proportion-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #price-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #payType-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #settleType-header="{ column }">
                    <span class="text-red pr-2">*</span
                    ><span>{{ column.label }}</span>
                  </template>
                  <template #period="{ row }">
                    <span>{{ rowIndex(row) }}</span>
                  </template>
                  <template #bankCard-form="{ row }">
                    <el-select
                      class="w-full"
                      v-model="row.bankCard"
                      :disabled="formDisabled"
                      placeholder="请选择收款账号"
                    >
                      <el-option
                        v-for="item in order_bank_card"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                        <div class="flex justify-between">
                          <span>{{ item.label }}</span
                          ><span>{{ item.value }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </template>
                  <template #menu="{ row, index }">
                    <el-button
                      plain
                      icon="Delete"
                      link
                      :disabled="
                        formDisabled || fieldDisabled.includes('回款明细')
                      "
                      @click="delRowRepayment(row, index)"
                      >删除</el-button
                    >
                  </template>
                  <template #empty>
                    <div>暂无数据</div>
                  </template>
                  <template #footer>
                    <el-row
                      class="bg-#f8f8f9 border-solid border-1 border-#ebeef5 pr-5"
                    >
                      <el-col :span="24" class="py-2 text-right">
                        总计划期次： {{ repaymentStatisticsData.num }}期
                        总回款占比：{{ repaymentStatisticsData.proportion }}%
                        总回款金额：¥
                        {{ repaymentStatisticsData.totalPrice }}
                      </el-col></el-row
                    >
                    <!-- <el-button
                      plain
                      type="primary"
                      icon="Plus"
                      class="w-full"
                      @click="addRowRepayment"
                      >添加期次</el-button
                    > -->
                  </template>
                </avue-crud>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 发票信息 -->
          <el-collapse-item
            name="发票信息"
            v-if="hidenDome.indexOf('发票信息') == -1"
          >
            <template #title>
              <TitleName
                title="发票信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="formData.invoiceType == '6' ? 12 : 24">
                <el-form-item
                  label="发票类型"
                  prop="invoiceType"
                  @change="
                    () => {
                      formData.headerType = 1
                    }
                  "
                >
                  <el-radio-group
                    v-model="formData.invoiceType"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('发票类型')
                    "
                  >
                    <el-radio-button
                      v-for="(item, index) in invoice_manage_type_order"
                      :label="item.value"
                      :key="index"
                      >{{ item.label }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.invoiceType == '6'">
                <el-form-item label="抬头类型" prop="headerType">
                  <el-radio-group
                    v-model="formData.headerType"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('抬头类型')
                    "
                  >
                    <el-radio-button
                      v-for="(item, index) in invoice_header"
                      :label="item.value"
                      :key="index"
                      >{{ item.label }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开票抬头" prop="invoiceTitle">
                  <el-input
                    v-model="formData.invoiceTitle"
                    placeholder="自动带入企业的开票抬头，可编辑联动的客户开票信息"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('开票抬头')
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="社会信用代码" prop="socialCreditCode">
                  <el-input
                    v-model="formData.socialCreditCode"
                    placeholder="自动带入，可编辑"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('社会信用代码')
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="接收手机" prop="invoicePhone">
                  <el-input
                    v-model="formData.invoicePhone"
                    :disabled="fieldDisabled.includes('接收手机')"
                    placeholder="自动带入，可编辑"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="接收邮箱" prop="receiveEmail">
                  <el-input
                    v-model="formData.receiveEmail"
                    :disabled="fieldDisabled.includes('接收邮箱')"
                    placeholder="自动带入，可编辑"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="发票日期" prop="invoiceDate">
                  <el-date-picker
                    style="width: 100%"
                    v-model="formData.invoiceDate"
                    type="date"
                    placeholder="发票日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12" v-if="formData.headerType == '1'">
                <el-form-item label="企业电话" prop="taxPhone">
                  <el-input
                    v-model="formData.taxPhone"
                    placeholder="企业电话"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('企业电话')
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.headerType == '1'">
                <el-form-item label="企业地址" prop="invoicePlace">
                  <el-input
                    v-model="formData.invoicePlace"
                    placeholder="企业地址"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('企业地址')
                    "
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="发票代码" prop="invoiceCode">
                  <el-input
                    v-model="formData.invoiceCode"
                    placeholder="填写发票代码"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12" v-if="formData.headerType == '1'">
                <el-form-item label="开户银行" prop="invoiceBank">
                  <el-input
                    v-model="formData.invoiceBank"
                    placeholder="填写开户银行"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('开户银行')
                    "
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="发票号码" prop="invoiceNumber">
                  <el-input
                    v-model="formData.invoiceNumber"
                    placeholder="填写发票号码"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12" v-if="formData.headerType == '1'">
                <el-form-item label="银行账号" prop="invoiceBankAccount">
                  <el-input
                    v-model="formData.invoiceBankAccount"
                    placeholder="自动带入，可编辑"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('银行账号')
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发票备注" prop="invoiceRemark">
                  <el-input
                    v-model="formData.invoiceRemark"
                    placeholder="发票备注"
                    :disabled="
                      formData.property == '1' ||
                      fieldDisabled.includes('发票备注')
                    "
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="所属税局" prop="taxdeptCode">
                  <el-tree-select
                    style="width: 100%"
                    v-model="formData.taxdeptCode"
                    :data="taxTreeOption"
                    :check-strictly="true"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                    node-key="id"
                    placeholder="填写所属税局"
                    value-key="id"
                    filterable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属税局分局" prop="taxBanck">
                  <el-input
                    v-model="formData.taxBanck"
                    placeholder="自动带入，可编辑"
                  />
                  <el-tree-select
                    style="width: 100%"
                    v-model="formData.taxdeptCode"
                    :data="taxTreeOption"
                    :check-strictly="true"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                    node-key="id"
                    placeholder="填写所属税局分局"
                    value-key="id"
                    filterable
                  />
                </el-form-item>
              </el-col> -->
            </el-row>
          </el-collapse-item>
          <!-- 其他信息 -->
          <el-collapse-item
            name="其他信息"
            v-if="hidenDome.indexOf('其他信息') == -1"
          >
            <template #title>
              <TitleName
                title="其他信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row :gutter="80" class="px-20">
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select
                    class="w-full"
                    v-model="formData.status"
                    placeholder="请选择状态"
                    :disabled="fieldDisabled.includes('状态')"
                  >
                    <el-option
                      v-for="item in order_status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="终止原因" prop="stopReason">
                  <el-input
                    v-model="formData.stopReason"
                    :disabled="fieldDisabled.includes('终止原因')"
                    placeholder="填写终止原因"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否期初" prop="isBeginningPeriod">
                  <el-radio-group
                    v-model="formData.isBeginningPeriod"
                    :disabled="fieldDisabled.includes('是否期初')"
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="来源系统单号" prop="sourceSystemNumber">
                  <el-input
                    v-model="formData.sourceSystemNumber"
                    :disabled="fieldDisabled.includes('来源系统单号')"
                    placeholder="填写来源系统单号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否初次购买" prop="isFirstBuy">
                  <el-radio-group
                    v-model="formData.isFirstBuy"
                    :disabled="fieldDisabled.includes('是否初次购买')"
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="来源系统名称" prop="sourceSystemName">
                  <el-input
                    v-model="formData.sourceSystemName"
                    :disabled="fieldDisabled.includes('来源系统名称')"
                    placeholder="填写来源系统名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="是否国际化经营"
                  prop="isInternationalOperate"
                >
                  <el-radio-group
                    v-model="formData.isInternationalOperate"
                    :disabled="fieldDisabled.includes('是否国际化经营')"
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="进出口类型" prop="importsExportsType">
                  <el-select
                    class="w-full"
                    v-model="formData.importsExportsType"
                    :disabled="fieldDisabled.includes('进出口类型')"
                    placeholder="请选择进出口类型"
                  >
                    <el-option
                      v-for="item in order_imports_exports_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="是否综管同步生产"
                  prop="isSynchronousProduce"
                >
                  <el-radio-group
                    v-model="formData.isSynchronousProduce"
                    :disabled="fieldDisabled.includes('是否综管同步生产')"
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收费方式" prop="chargeType">
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('收费方式')"
                    v-model="formData.chargeType"
                    placeholder="请选择收费方式"
                  >
                    <el-option
                      v-for="item in order_charge_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="借出转销售" prop="loanToSell">
                  <el-radio-group
                    v-model="formData.loanToSell"
                    :disabled="fieldDisabled.includes('借出转销售')"
                  >
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="往来业务类型" prop="transactionType">
                  <el-select
                    class="w-full"
                    :disabled="fieldDisabled.includes('往来业务类型')"
                    v-model="formData.transactionType"
                    placeholder="请选择往来业务类型"
                  >
                    <el-option
                      v-for="item in transaction_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注信息" prop="remark">
                  <el-input
                    v-model="formData.remark"
                    :disabled="fieldDisabled.includes('备注信息')"
                    placeholder="填写备注信息"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.createName">
                <el-form-item label="填单人" prop="createName">
                  <el-input
                    disabled
                    v-model="formData.createName"
                    placeholder="系统自动带入新建的用户名称"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>

    <!-- 发票信息弹窗 -->
    <el-dialog title="发票信息" v-model="showInvoice" width="1000px">
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        :disabled="formDisabled"
      >
        <el-row :gutter="40">
          <el-col :span="formData.invoiceType == '6' ? 12 : 24">
            <el-form-item
              label="发票类型"
              prop="invoiceType"
              @change="
                () => {
                  formData.headerType = 1
                }
              "
            >
              <el-radio-group
                v-model="formData.invoiceType"
                :disabled="formData.property == '1'"
              >
                <el-radio-button
                  v-for="(item, index) in invoice_manage_type_order"
                  :label="item.value"
                  :key="index"
                  >{{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.invoiceType == '6'">
            <el-form-item label="抬头类型" prop="headerType">
              <el-radio-group
                v-model="formData.headerType"
                :disabled="formData.property == '1'"
              >
                <el-radio-button
                  v-for="(item, index) in invoice_header"
                  :label="item.value"
                  :key="index"
                  >{{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票抬头" prop="invoiceTitle">
              <el-input
                v-model="formData.invoiceTitle"
                placeholder="自动带入企业的开票抬头，可编辑联动的客户开票信息"
                :disabled="formData.property == '1'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="社会信用代码" prop="socialCreditCode">
              <el-input
                v-model="formData.socialCreditCode"
                placeholder="自动带入，可编辑"
                :disabled="formData.property == '1'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接收手机" prop="invoicePhone">
              <el-input
                v-model="formData.invoicePhone"
                placeholder="自动带入，可编辑"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接收邮箱" prop="receiveEmail">
              <el-input
                v-model="formData.receiveEmail"
                placeholder="自动带入，可编辑"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="发票日期" prop="invoiceDate">
              <el-date-picker
                style="width: 100%"
                v-model="formData.invoiceDate"
                type="date"
                placeholder="发票日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12" v-if="formData.headerType == '1'">
            <el-form-item label="企业电话" prop="taxPhone">
              <el-input
                v-model="formData.taxPhone"
                placeholder="企业电话"
                :disabled="formData.property == '1'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.headerType == '1'">
            <el-form-item label="企业地址" prop="invoicePlace">
              <el-input
                v-model="formData.invoicePlace"
                placeholder="企业地址"
                :disabled="formData.property == '1'"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input
                v-model="formData.invoiceCode"
                placeholder="填写发票代码"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12" v-if="formData.headerType == '1'">
            <el-form-item label="开户银行" prop="invoiceBank">
              <el-input
                v-model="formData.invoiceBank"
                placeholder="填写开户银行"
                :disabled="formData.property == '1'"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input
                v-model="formData.invoiceNumber"
                placeholder="填写发票号码"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12" v-if="formData.headerType == '1'">
            <el-form-item label="银行账号" prop="invoiceBankAccount">
              <el-input
                v-model="formData.invoiceBankAccount"
                placeholder="自动带入，可编辑"
                :disabled="formData.property == '1'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票备注" prop="invoiceRemark">
              <el-input
                v-model="formData.invoiceRemark"
                placeholder="发票备注"
                :disabled="formData.property == '1'"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="所属税局" prop="taxdeptCode">
              <el-tree-select
                style="width: 100%"
                v-model="formData.taxdeptCode"
                :data="taxTreeOption"
                :check-strictly="true"
                :props="{
                  value: 'id',
                  label: 'label',
                  children: 'children'
                }"
                node-key="id"
                placeholder="填写所属税局"
                value-key="id"
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属税局分局" prop="taxBanck">
              <el-input
                v-model="formData.taxBanck"
                placeholder="自动带入，可编辑"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <slot name="bottomBtn"></slot>
          <!-- <el-button @click="cancelUpload">取消</el-button> -->
          <el-button type="primary" @click="saveInvoice">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 物料选择弹窗 -->
    <ProductDialog
      v-model="dialogData.open"
      :dialogData="dialogData"
      @getData="productDialogFn"
    />

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    />

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    />

    <!-- 提交审批 -->
    <SubmissionProcess
      :dialog-param="examineParam"
      :flowOptions="flowOptions"
      @initiate="handleClose('initiate')"
      @close="handleClose('examine')"
    />

    <!-- 关联合同 -->
    <SelectContract
      :dialogParam="paramsContract"
      @close="paramsContract.open = false"
      @ok="saveFn"
    />
    <!-- 选择合同 -->
    <!-- <RelatedContract
      :relatedParams="params"
      @closeDialog="closeDialog"
      @relatedOver="relatedOver"
      @editContract="editContract"
      ref="relatedContract"
    >
      <template #bottomBtn>
        <el-input
          v-show="showInput"
          placeholder="请输入合同备注"
          v-model="formData.contractRemark"
          class="mr-10px"
          style="width: 300px"
        />
        <el-button @click="showInput = !showInput" type="primary"
          >合同备注</el-button
        >
        <el-button @click="uploadConstarct" type="primary">上传合同</el-button>
      </template>
    </RelatedContract> -->

    <!-- 选择项目 -->
    <RelatedProject
      :relatedParams="proParams"
      @closeDialog="closePro"
      @relatedOver="relatedPro"
    />

    <!-- 选择会员 -->
    <SelectVIP
      :dialogParam="dialogVIP"
      @ok="selectVIP"
      @close="
        val => {
          dialogVIP.open = false
        }
      "
    />

    <!-- 上传合同 -->
    <!-- <el-dialog title="上传合同" v-model="showUpload">
      <el-upload
        class="upload-demo"
        action="#"
        :before-upload="beforeUpload"
        :http-request="handleFileChange"
        accept=".rar, .zip, .doc, .docx, .pdf"
        :show-file-list="false"
        :multiple="true"
      >
        <el-button type="primary" style="font-size: 14px"
          ><el-icon> <UploadFilled /> </el-icon>上传合同</el-button
        >
        <template #tip>
          <span class="el-upload__tip ml-5px">
            支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
          </span>
        </template>
      </el-upload>
      <div class="text-14px mt-10px" style="width: 100%">
        <div v-for="(item, index) in fileList" :key="item.fileId">
          <span style="color: #409eff" :href="item.url">{{
            item.origFileName
          }}</span>
          <el-button text plain @click="delFileName(index)">删除</el-button>
        </div>
      </div>
      <template #footer>
        <div>
          <slot name="bottomBtn"></slot>
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="finishedUpload">确定</el-button>
        </div>
      </template>
    </el-dialog> -->

    <!-- 关联订单 -->
    <RelatedOrder
      :relatedParams="orderParams"
      @closeDialog="ordCloseDialog"
      @relatedOver="ordRelatedOver"
    />

    <!-- 发票弹窗 -->
    <InvoiceDialog
      v-model="redInvoiceParam.open"
      :dialogData="redInvoiceParam"
      @getData="redDialogFn"
    />

    <!-- 签购单 -->
    <SalesSlip v-if="salesSlipDia.open" :dialogParam="salesSlipDia" />
  </div>
</template>
<script setup name="SalesOrderForm">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useTagsViewStore from '@/store/modules/tagsView'
import {
  crudOption, // 子表公用配置
  order_business_type, //订单业务分类
  order_status, //订单状态
  order_biz_type, //业务类型
  yes_or_no, //是否
  pay_type, //付款方式
  settle_type, //结算方式
  invoice_manage_type_order, //订单发票类型
  invoice_header, //抬头类型
  measurement_unit, //产品单位
  order_property, //订单属性
  transaction_type, //往来业务类型
  order_transport_type, //订单运输方式
  order_indemnity_percent, //订单违约赔偿率
  order_transport_man, //订单运费承担方
  order_sell_group, //订单销售分组
  order_agency_dept, //订单代理机构
  order_pro_type, //订单产品类型
  order_charge_type, //订单收费方式
  order_bank_card, //订单收款账号
  order_imports_exports_type, //订单进出口类型
  order_hierarchy, //层次
  improve_form, //提升形式
  order_library, //培训产业继续教育所属库
  library_status, //入库情况
  online_offline, //线上/线下
  train_course_name, //培训课程名称
  order_process, //订单业务流程
  enter_date, //入学时间
  keep_account_type, //代理记账业务分类
  keep_account_content, //代账服务内容
  certificateName, // 报考证书名称
  loadingSelect, //远程检索loading
  companyOption, //所属公司
  companyNoPrivOption, //所属公司无权限
  departmentNoPrivOption, //当前公司所有部门树结构
  userBusinessTypeOption, //用户业务类型树
  projectOptionsLimitEnt, //项目数据
  queryProjectLimitEnt, //检索项目
  contractOptionsLimitEnt, //合同数据
  queryContractLimitEnt, //检索合同数据
  parentOptions, // 客户数据
  queryCustomer, // 检索客户数据
  contactsOptionsLimitEnt, // 联系人数据
  queryContactsLimitEnt, // 检索联系人数据
  queryWhsLimitEnt, // 检索仓库数据
  whsOptLimitEnt //仓库数据
} from '@/hooks/dict/order'
import { getInventory } from '@/api/warehouseManage/warehouse'
import { getUser } from '@/api/system/user'
import { getDetailByNumber } from '@/api/invoiceManage/invoice'
import {
  setSalesOrder,
  getSalesOrder,
  importData,
  orderGoFinish
} from '@/api/indentManage/indent'
import {
  getCustomerEditInfo,
  createCustomer, //创建客户
  getCustomerInfo //获取客户详情
} from '@/api/customerManage/customerList'
import { delRepaymentPlan } from '@/api/repaymentManage/repayment'
import {
  isMoneyNot,
  isMoneyNegative,
  validateLen,
  validatePhoneNot,
  maxDecimals,
  isNum
} from '@/utils/validate'
import {
  skipToError,
  getTreeNodeByParam,
  getPricipalId,
  myToFixed
} from '@/utils/commo'
import useUserStore from '@/store/modules/user'

import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import {
  listProcess,
  getBusinessProStatus,
  getNodeData
} from '@/api/workflow/process'
import {
  uploadFile,
  delFile,
  contractInfoSave,
  contractInfoUpdate,
  contractDetails
} from '@/api/salesManage/contractManage'
import SalesSlip from './salesSlip'

import useCommonStore from '@/store/modules/common'
const commonStore = useCommonStore()

// 培训产业配置
const industry = {
  '培训产业-继续教育': { name: '继续教育', field: 'continuingEducation' },
  '培训产业-会员': { name: '会员', field: 'member' },
  '培训产业-证书': { name: '证书', field: 'certificate' },
  '培训产业-单课程': { name: '单课程', field: 'course' },
  '培训产业-学历提升': { name: '学历提升', field: 'educationPromotion' },
  '培训产业-1+X': { name: '1+X', field: 'onex' },
  云财税软件: { name: '云财税软件', field: 'member' },
  云财税软件运维费: { name: '云财税软件运维费', field: 'member' }
}

const examineParam = ref({}) // 传递的参数
const isExamine = ref(true) // 判断是否走审批按钮
const flowOptions = ref([]) // 该业务的流程数据
const isCanStart = ref(true) // 判断该业务是否可以审批发起 以及办理详情 访问的时候不能审批 ===》针对编辑页面  办理详情
const processStatus = ref('') // 保存流程状态

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy, type } = getCurrentInstance()
const { product_property } = proxy.useDict('product_property')
const props = defineProps({
  salesOrderId: {
    type: [Number, String],
    require: true
  },
  id: {
    type: [Number, String],
    require: false
  }
})

// 获取培训产业模板链接/file/系统模板文件/培训产业登记表V1_20230728155654A001.xls
const downUrl = async () => {
  const url = await commonStore.getUploadTemplateDown('saleOrder_file_down')
  // console.info('url', url)
  window.open(url, '_blank')
}
// 是否隐藏诺账通会员权益
const isHideNZT = ref(true)
const formData = ref({
  operationType: '1', //操作类型默认1手工录入2导入
  deptId: userStore.userInfo.orgId, //所属公司默认
  deptName: userStore.userInfo.orgIdCn, //所属公司默认
  sourceOrgId: userStore.userInfo.orgId, //订单统计归属单位
  businessType: '',
  keepAccountContentArr: [],
  property: '0',
  bizType: 'PTXS',
  // proType: '0',
  customerId: '',
  customerName: '',
  invoiceType: '6', //发票类型，默认数电普通电子发票
  headerType: '1', //抬头类型，默认企业
  productInfoList: [], //产品列表
  continuingEducationList: [], //培训产业-继续教育列表
  memberList: [], //培训产业-会员列表
  certificateList: [], //培训产业-证书列表
  courseList: [], //培训产业-单课程
  educationPromotionList: [], //培训产业-学历提升
  onexList: [], //培训产业-1+X
  repaymentPlanList: [], //回款列表
  customerType: 'customer', //客户选择下拉
  _transactionId: `U${userStore.userInfo.userId}`, //销售人员默认
  transactionName: `${userStore.userInfo.nickName}`, //销售人员默认
  transactionDept: userStore.userInfo.dept.deptId, //业务部门默认
  status: '1', //状态默认填单
  receiptsDate: proxy.parseTime(new Date(new Date().getTime())) //单据日期默认
})
const data = reactive({
  formRules: {
    title: [
      {
        required: true,
        message: '请输入订单标题',
        trigger: 'blur'
      },
      validateLen(100)
    ],
    bizType: [
      {
        required: true,
        message: '请选择业务类型',
        trigger: 'change'
      }
    ],
    property: [
      {
        required: true,
        message: '请选择订单属性',
        trigger: 'change'
      }
    ],
    oppositeName: [
      {
        required: true,
        message: '请选择关联订单',
        trigger: 'change'
      }
    ],
    keepAccountType: [
      {
        required: true,
        message: '请选择代账业务分类',
        trigger: 'change'
      }
    ],
    keepAccountContentArr: [
      {
        required: true,
        message: '请选择服务内容',
        trigger: 'change'
      }
    ],
    keepAccountOtherService: [
      {
        required: computed(() => {
          return formData.value.keepAccountContentArr?.includes('其他服务')
        }),
        message: '请输入其他服务',
        trigger: ['blur', 'change']
      }
    ],
    contractSum: [
      {
        required: true,
        message: '请输入合同金额',
        trigger: ['blur', 'change']
      }
    ],
    contractTimeBegin: [
      {
        required: true,
        message: '请选择合同时间起',
        trigger: 'change'
      }
    ],
    contractTimeEnd: [
      {
        required: true,
        message: '请选择合同时间止',
        trigger: 'change'
      }
    ],
    contractNames: [
      {
        required: computed(() => {
          let val =
            formData.value.productInfoList &&
            formData.value.productInfoList.some(
              item => item.number == 'H00030000000189_7501'
            )
          return val
        }),
        message: '请选择服务内容',
        trigger: 'change'
      }
    ],
    flushRedReason: [
      {
        required: true,
        message: '请输入冲红原因',
        trigger: 'change'
      }
    ],
    customerId: [
      {
        required: true,
        message: '请选择客户名称',
        trigger: 'blur'
      }
    ],
    customerName: [
      {
        required: true,
        message: '请选择客户名称',
        trigger: ['blur', 'change']
      }
    ],
    cusLinkId: [
      {
        required: true,
        message: '请选择联系人名称',
        trigger: 'change'
      }
    ],
    cusLinkName: [
      {
        required: true,
        message: '请选择联系人名称',
        trigger: 'change'
      }
    ],
    linkPhone: [
      {
        required: true,
        message: '请选择联系方式',
        trigger: 'change'
      }
    ],
    processKey: [
      {
        required: true,
        message: '请选择业务流程',
        trigger: 'change'
      }
    ],
    proProperty: [
      {
        required: true,
        message: '请选择产品属性',
        trigger: 'change'
      }
    ],
    number: [
      {
        required: false,
        message: '请输入订单编号',
        trigger: 'blur'
      }
    ],
    customerCreditCode: [
      {
        required: true,
        message: computed(() => {
          return formData.value.customerType == 'customer'
            ? '请输入客户社会信用代码'
            : '请输入身份证'
        }),
        trigger: 'change'
      }
    ],
    repaymentDate: [
      {
        required: true,
        message: '请选择回款日期',
        trigger: 'change'
      }
    ],
    businessType: [
      {
        required: true,
        message: '请选择所属业务分类',
        trigger: 'change'
      }
    ],
    receiptsDate: [
      {
        required: true,
        message: '请选择单据日期',
        trigger: 'change'
      }
    ],
    deptId: [
      {
        required: true,
        message: '请选择所属公司',
        trigger: 'change'
      }
    ],
    sourceOrgId: [
      {
        required: true,
        message: '请选择订单统计归属单位',
        trigger: 'change'
      }
    ],
    contractOrderNumber: [
      {
        required: true,
        message: '请选择合同(订单)编号',
        trigger: 'change'
      }
    ],
    warehouse: [
      {
        required: true,
        message: '请选择仓库',
        trigger: 'change'
      }
    ],
    transactionDept: [
      {
        required: true,
        message: '请选择业务部门',
        trigger: 'change'
      }
    ],
    _transactionId: [
      {
        required: true,
        message: '请选择销售人员',
        trigger: 'change'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入订单金额',
        trigger: 'blur'
      },
      {
        validator: computed(() => {
          return formData.value.property == '1' ? isMoneyNegative : isMoneyNot
        })
      }
    ],
    receiveEmail: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change']
      }
    ],
    invoicePhone: [
      {
        validator: validatePhoneNot,
        message: '请输入发票信息-接收手机号'
      }
    ]
  },
  uploadLoading: false, //导入数据按钮loading
  activeNames: [
    '订单主体',
    '基本信息',
    '代账信息',
    '培训产业特殊信息',
    '产品信息',
    '继续教育',
    '会员',
    '证书',
    '单课程',
    '学历'
  ],
  crudOptionProduct: {
    ...crudOption,
    column: [
      {
        label: '产品名称',
        prop: 'name',
        cell: false,
        rules: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ]
        // hide:true
      },
      {
        label: '产品编号',
        prop: 'number',
        cell: false
      },
      {
        label: '会员权益',
        prop: 'membershipLevel',
        minWidth: '200',
        cell: true,
        hide: computed(() => {
          let isNzt = true
          let business = order_business_type.value.filter(e => {
            return formData.value.businessType == e.value
          })
          try {
            isNzt = business[0].value != '诺账通'
          } catch (error) {}
          return isNzt
        })
      },
      {
        label: '仓库',
        prop: 'warehouse',
        cell: true,
        width: '150',
        rules: [
          {
            required: true,
            message: '请输入仓库',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '库存量',
        prop: 'inventory',
        cell: false
      },
      {
        label: '实际售价',
        prop: 'actualPrice',
        type: 'number',
        min: 0,
        class: 'w-full',
        width: '120',
        controls: false,
        rules: [
          {
            required: true,
            message: '请输入实际售价',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              maxDecimals(rule, value, callback, 6)
            }
          }
        ],
        blur: val => {
          const { value, row } = val
          // console.log('实际售价val==>>', val)
          // maxSellingPrice 最高价 minSellingPrice最低价
          // console.log(
          //   '最高==>',
          //   row.minSellingPrice,
          //   typeof row.minSellingPrice
          // )
          // console.log(
          //   '最底==>',
          //   row.maxSellingPrice,
          //   typeof row.maxSellingPrice
          // )
          // console.log('value==>', value, typeof value)
          if (
            (row.minSellingPrice <= value && value <= row.maxSellingPrice) ||
            (!row.minSellingPrice && value <= row.maxSellingPrice) ||
            (row.minSellingPrice <= value && !row.maxSellingPrice) ||
            (!row.minSellingPrice && !row.maxSellingPrice)
          ) {
            // console.log('在范围')
            row.discount = row.price == 0 ? 0 : (1 - value / row.price) * 100
            row.totalPrice = myToFixed(Number(value) * Number(row.num), 6)
          } else {
            // let minSellingPrice = row.minSellingPrice
            // let maxSellingPrice = row.maxSellingPrice
            // console.log('不在范围')
            // `实际售价不能低于最低销售价:${row.minSellingPrice}以及最高销售价:${row.maxSellingPrice}`
            proxy.$modal.msgWarning(
              '销售价格溢出了允许的价格区间，请调整销售价格！' /* +
                `${minSellingPrice ? '最低销售价:' + minSellingPrice : ''}` +
                `${maxSellingPrice ? '最低销售价:' + maxSellingPrice : ''}` */
            )
            row.actualPrice = '' //row.price//实际售价不用自动带进来
            row.discount = 0
          }
        },
        cell: true
      },
      // {
      //   label: '折扣(%)',
      //   prop: 'discount',
      //   type: 'number',
      //   min: 0,
      //   max: 100,
      //   width: '120',
      //   class: 'w-full',
      //   controls: false,
      //   precision: 0,
      //   rules: [
      //     {
      //       required: true,
      //       message: '请输入折扣(%)',
      //       trigger: 'blur'
      //     }
      //   ],
      //   blur: val => {
      //     const { value, row } = val
      //     // console.log('折扣value==>>', value, row)
      //     let indirect = Number(myToFixed((1 - value / 100) * row.price, 6))
      //     if (
      //       (row.minSellingPrice <= indirect &&
      //         indirect <= row.maxSellingPrice) ||
      //       (!row.minSellingPrice && indirect <= row.maxSellingPrice) ||
      //       (row.minSellingPrice <= indirect && !row.maxSellingPrice) ||
      //       (!row.minSellingPrice && !row.maxSellingPrice)
      //     ) {
      //       // console.log('在范围')
      //       row.actualPrice = Number(
      //         myToFixed((1 - value / 100) * row.price, 6)
      //       )
      //       row.totalPrice = myToFixed(
      //         Number(row.actualPrice) * Number(row.num),
      //         6
      //       )
      //     } else {
      //       // console.log('不在范围')
      //       // `实际售价不能低于最低销售价:${row.minSellingPrice}以及最高销售价:${row.maxSellingPrice}`
      //       proxy.$modal.msgWarning(
      //         '销售价格溢出了允许的价格区间，请调整销售价格！'
      //       )
      //       //row.actualPrice = row.price //实际售价不用自动带进来
      //       row.discount = 0
      //     }
      //   },
      //   cell: true
      // },
      {
        label: '数量',
        prop: 'num',
        type: 'number',
        // min: 0, //由于是红蓝单所以可负数
        class: 'w-full',
        controls: false,
        // precision: 0,
        rules: [
          {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              maxDecimals(rule, value, callback, 6)
            }
          }
        ],
        blur: val => {
          const { value, row } = val
          row.totalPrice = myToFixed(Number(value) * Number(row.actualPrice), 6)
        },
        cell: true
      },
      {
        label: '标准单价',
        prop: 'price',
        rules: [
          {
            required: true,
            message: '请输入标准单价',
            trigger: 'blur'
          }
        ],
        cell: false
      },
      {
        label: '规格型号',
        prop: 'specification',
        cell: false
      },
      {
        label: '单位',
        prop: 'unit',
        type: 'select',
        dicData: measurement_unit,
        cell: false
      },
      {
        label: '总价(元)',
        prop: 'totalPrice',
        cell: true,
        controls: false,
        rules: [
          {
            required: true,
            message: '请输入总价',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              maxDecimals(rule, value, callback, 6)
            }
          }
        ],
        blur: val => {
          const { value, row } = val
          if (!row.num) return proxy.$modal.msgError('请先输入数量')
          row.actualPrice = myToFixed(Number(value) / Number(row.num), 6)
        }
      },
      {
        label: '服务时间',
        prop: 'serviceDateArr',
        type: 'daterange',
        class: 'daterangeClass',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间',
        cell: true,
        minWidth: '240',
        rules: [
          {
            required: false,
            message: '请输入服务时间',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              if (value.length > 0 && !value[0] && value[1]) {
                return callback(new Error('请选择服务开始时间'))
              } else if (value.length > 0 && value[0] && !value[1]) {
                return callback(new Error('请选择服务结束时间'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      {
        label: '赠品',
        prop: 'present',
        // type: 'textarea',
        // maxRows: 1,
        rules: [
          {
            required: false,
            message: '请输入赠品',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '备注',
        prop: 'remark',
        type: 'textarea',
        minRows: 2,
        clearable: true,
        // maxRows: 1,
        minWidth: '100',
        rules: [
          {
            required: false,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '分机号',
        prop: 'extensionNo',
        // hide: formData.value.proProperty == '1',
        type: 'input',
        min: 0,
        class: 'w-full',
        controls: false,
        // precision: 0,
        rules: [
          {
            required: false,
            message: '请输入数量',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              isNum(rule, value, callback)
            }
          }
        ],
        cell: true
      }
    ]
  },
  crudOptionBusiness: {
    /* 继续教育列表配置 */
    continuingEducationOption: {
      ...crudOption,
      index: true,
      indexLabel: '序号',
      indexWidth: '60',
      column: [
        {
          label: '客户名称',
          prop: 'contactName',
          fixed: true,
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请输入客户名称',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '身份证号码',
          prop: 'idNumber',
          minWidth: '200',
          cell: true,
          rules: [
            {
              required: true,
              message: '请输入身份证号码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '办理年份',
          prop: 'transactYear',
          type: 'year',
          format: 'YYYY',
          valueFormat: 'YYYY',
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请选择办理年份',
              trigger: 'change'
            }
          ]
        },
        {
          label: '电话号码',
          prop: 'contactNumber',
          cell: true,
          width: '150',
          rules: [
            {
              required: true,
              message: '请输入电话号码',
              trigger: 'blur'
            }
          ]
        },
        // {
        //   label: '学历层次',
        //   prop: 'hierarchy',
        //   type: 'select',
        //   minWidth: '150',
        //   dicData: order_hierarchy,
        //   cell: true
        // },
        // {
        //   label: '提升形式',
        //   prop: 'improveForm',
        //   type: 'select',
        //   minWidth: '150',
        //   dicData: improve_form,
        //   cell: true
        // },
        // {
        //   label: '报考学校',
        //   prop: 'applySchool',
        //   cell: true,
        //   width: '150',
        //   rules: [
        //     {
        //       required: false,
        //       message: '请输入报考学校',
        //       trigger: 'blur'
        //     }
        //   ]
        // },
        // {
        //   label: '报考专业',
        //   prop: 'applyMajor',
        //   cell: true,
        //   width: '150',
        //   rules: [
        //     {
        //       required: false,
        //       message: '请输入报考专业',
        //       trigger: 'blur'
        //     }
        //   ]
        // },
        {
          label: '入库情况',
          prop: 'libraryStatus',
          type: 'select',
          minWidth: '150',
          dicData: library_status,
          cell: true,
          rules: [
            {
              required: true,
              message: '请选择入库情况',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '所属库',
          prop: 'library',
          type: 'select',
          minWidth: '150',
          dicData: order_library,
          cell: true,
          rules: [
            {
              required: true,
              message: '请选择所属库',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '备注',
          prop: 'remark',
          // type: 'textarea',
          // maxRows: 1,
          rules: [
            {
              required: false,
              message: '请输入备注',
              trigger: 'blur'
            }
          ],
          cell: true
        }
      ]
    },
    /* 会员列表配置 */
    memberOption: {
      ...crudOption,
      column: [
        {
          label: '会员名称',
          prop: 'contactName',
          fixed: true,
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请输入客户名称',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '电话号码',
          prop: 'contactNumber',
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请输入电话号码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '会员等级',
          prop: 'membershipLevel',
          // type: 'select',
          minWidth: '200',
          // dicData: membership_level,
          cell: true
        },
        // {
        //   label: '权益内容',
        //   prop: 'equityContent',
        //   cell: true,
        //   minWidth: '150'
        // },
        // {
        //   label: '首次购买服务时间',
        //   prop: 'firstDate',
        //   type: 'date',
        //   format: 'YYYY-MM-DD',
        //   valueFormat: 'YYYY-MM-DD',
        //   cell: true,
        //   minWidth: '150'
        // },
        {
          label: '服务时间',
          prop: 'serviceDateArr',
          type: 'daterange',
          class: 'daterangeClass',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          cell: true,
          minWidth: '240'
        },
        {
          label: '线上权益是否开通',
          prop: 'isActivate',
          type: 'select',
          minWidth: '130',
          dicData: yes_or_no,
          cell: true
        },
        {
          label: '教材赠送',
          prop: 'sendTextbook',
          cell: true,
          minWidth: '150'
        },
        {
          label: '微信昵称',
          prop: 'wechatNickname',
          cell: true,
          minWidth: '150'
        },
        {
          label: '所在群',
          prop: 'groupChat',
          cell: true,
          minWidth: '150'
        },
        {
          label: '听课情况',
          prop: 'lectureSituation',
          cell: true,
          minWidth: '150'
        },
        {
          label: '备注',
          prop: 'remark',
          // type: 'textarea',
          // maxRows: 1,
          rules: [
            {
              required: false,
              message: '请输入备注',
              trigger: 'blur'
            }
          ],
          cell: true
        }
      ]
    },
    /* 证书列表配置 */
    certificateOption: {
      ...crudOption,
      column: [
        {
          label: '客户名称',
          prop: 'contactName',
          fixed: true,
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请输入客户名称',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '身份证号码',
          prop: 'idNumber',
          minWidth: '200',
          cell: true,
          rules: [
            {
              required: true,
              message: '请输入身份证号码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '电话号码',
          prop: 'contactNumber',
          placeholder: '请输入电话号码',
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请输入电话号码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '报考证书名称',
          prop: 'certificateName',
          type: 'tree',
          minWidth: '150',
          dicData: certificateName,
          cell: true
        },
        {
          label: '培训服务时间',
          prop: 'trainServiceDateArr',
          type: 'daterange',
          class: 'daterangeClass',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          cell: true,
          minWidth: '240'
        },
        {
          label: '收件地址',
          prop: 'address',
          cell: true,
          minWidth: '150'
        },
        {
          label: '备注',
          prop: 'remark',
          // type: 'textarea',
          // maxRows: 1,
          rules: [
            {
              required: false,
              message: '请输入备注',
              trigger: 'blur'
            }
          ],
          cell: true
        }
      ]
    },
    /* 单课程列表配置 */
    courseOption: {
      ...crudOption,
      column: [
        {
          label: '客户名称',
          prop: 'contactName',
          fixed: true,
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请输入客户名称',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '电话号码',
          prop: 'contactNumber',
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请输入电话号码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '课程名称',
          prop: 'courseName',
          type: 'select',
          class: 'w-full',
          dicData: train_course_name,
          cell: true,
          minWidth: '150'
        },
        {
          label: '线上/线下',
          prop: 'onlineOffline',
          type: 'select',
          class: 'w-full',
          minWidth: '130',
          dicData: online_offline,
          cell: true
        },
        {
          label: '备注',
          prop: 'remark',
          rules: [
            {
              required: false,
              message: '请输入备注',
              trigger: 'blur'
            }
          ],
          cell: true
        }
      ]
    },
    /* 学历提升列表配置 */
    educationPromotionOption: {
      ...crudOption,
      column: [
        {
          label: '客户名称',
          prop: 'contactName',
          fixed: true,
          cell: true,
          minWidth: '150',
          rules: [
            {
              required: true,
              message: '请输入客户名称',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '身份证号码',
          prop: 'idNumber',
          minWidth: '200',
          cell: true,
          rules: [
            {
              required: true,
              message: '请输入身份证号码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '电话号码',
          prop: 'contactNumber',
          cell: true,
          width: '150',
          rules: [
            {
              required: true,
              message: '请输入电话号码',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '学历层次',
          prop: 'hierarchy',
          type: 'select',
          minWidth: '150',
          dicData: order_hierarchy,
          cell: true
        },
        {
          label: '提升形式',
          prop: 'improveForm',
          type: 'select',
          minWidth: '150',
          dicData: improve_form,
          cell: true
        },
        {
          label: '报考学校',
          prop: 'applySchool',
          cell: true,
          width: '150',
          rules: [
            {
              required: false,
              message: '请输入报考学校',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '报考专业',
          prop: 'applyMajor',
          cell: true,
          width: '150',
          rules: [
            {
              required: false,
              message: '请输入报考专业',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '服务时间',
          prop: 'serviceDateArr',
          type: 'daterange',
          class: 'daterangeClass',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          startPlaceholder: '开始时间',
          endPlaceholder: '结束时间',
          cell: true,
          minWidth: '240'
        },
        {
          label: '报名时间',
          prop: 'registerDate',
          type: 'date',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          cell: true,
          minWidth: '150'
        },
        {
          label: '入学时间',
          prop: 'enterDate',
          type: 'select',
          minWidth: '150',
          dicData: enter_date,
          cell: true
        },
        {
          label: '备注',
          prop: 'remark',
          // type: 'textarea',
          // maxRows: 1,
          rules: [
            {
              required: false,
              message: '请输入备注',
              trigger: 'blur'
            }
          ],
          cell: true
        }
      ]
    },
    /* 1+X列表配置 */
    onexOption: {
      ...crudOption,
      column: [
        {
          label: '院校名称',
          prop: 'collegeName',
          minWidth: '200',
          cell: true,
          rules: [
            {
              required: true,
              message: '请输入院校名称',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '院校税号',
          prop: 'collegeTaxcode',
          minWidth: '200',
          cell: true,
          rules: [
            {
              required: true,
              message: '请输入院校税号',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '联系人',
          prop: 'contactName',
          cell: true,
          width: '150',
          rules: [
            {
              required: false,
              message: '请输入联系人',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '联系电话',
          prop: 'contactNumber',
          cell: true,
          width: '150',
          rules: [
            {
              required: false,
              message: '请输入联系电话',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '考试人数 ',
          prop: 'examNum',
          cell: true,
          width: '150',
          rules: [
            {
              required: false,
              message: '请输入考试人数 ',
              trigger: 'blur'
            }
          ]
        },
        {
          label: '单价 ',
          prop: 'unitPrice',
          type: 'number',
          min: 0,
          class: 'w-full',
          width: '90',
          controls: false,
          rules: [
            {
              required: false,
              message: '请输入单价 ',
              trigger: 'blur'
            },
            {
              validator: isMoneyNot
            }
          ],
          cell: true
        },
        {
          label: '金额',
          prop: 'amount',
          type: 'number',
          min: 0,
          class: 'w-full',
          width: '90',
          controls: false,
          rules: [
            {
              required: false,
              message: '请输入金额',
              trigger: 'blur'
            },
            {
              validator: isMoneyNot
            }
          ],
          cell: true
        },
        {
          label: '考试时间',
          prop: 'examDate',
          type: 'date',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          cell: true,
          minWidth: '150'
        },
        {
          label: '备注',
          prop: 'remark',
          // type: 'textarea',
          // maxRows: 1,
          rules: [
            {
              required: false,
              message: '请输入备注',
              trigger: 'blur'
            }
          ],
          cell: true
        }
      ]
    }
  }, //业务分类子表配置
  crudOptionRepayment: {
    ...crudOption,
    menuWidth: 80,
    column: [
      {
        label: '期次',
        prop: 'period',
        width: '50',
        rules: [
          {
            required: true,
            message: '期次',
            trigger: 'blur'
          }
        ],
        value: '1',
        cell: false
      },
      {
        label: '计划回款日期',
        prop: 'repaymentPlanDate',
        type: 'date',
        cell: true,
        valueFormat: 'YYYY-MM-DD',
        rules: [
          {
            required: true,
            message: '请输入计划回款日期',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '计划回款占比(%)',
        prop: 'proportion',
        type: 'number',
        min: 0,
        max: 100,
        class: 'w-full',
        precision: 0,
        rules: [
          {
            required: true,
            message: '请输入计划回款占比(%)',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '计划回款金额(元)',
        prop: 'price',
        rules: [
          {
            required: true,
            message: '请输入计划回款金额(元)',
            trigger: 'blur'
          },
          {
            validator: isMoneyNot
          }
        ],
        cell: true
      },
      {
        label: '付款方式',
        prop: 'payType',
        type: 'select',
        dicData: pay_type,
        rules: [
          {
            required: true,
            message: '请选择付款方式',
            trigger: 'change'
          }
        ],
        cell: true
      },
      {
        label: '结算方式',
        prop: 'settleType',
        type: 'select',
        dicData: settle_type,
        rules: [
          {
            required: true,
            message: '请选择付款方式',
            trigger: 'change'
          }
        ],
        cell: true
      },
      {
        label: '收款账号',
        prop: 'bankCard',
        cell: true
      },
      {
        label: '备注',
        prop: 'remark',
        rules: [
          {
            required: false,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        cell: true
      }
    ]
  },
  countCrudData: {},
  repaymentStatisticsData: {},
  dialogData: {
    open: false
  },
  showTrainingIndustry: '',
  userOption: {
    transactionId: [
      {
        uuid: `U${userStore.userInfo.userId}`,
        id: userStore.userInfo.userId,
        label: userStore.userInfo.nickName
      }
    ]
  }, //人员选择下拉userOption['transactionId']"
  customerOption: {}, //客户选择下拉
  dialogParam: {},
  dialogParamA: {},
  dialogVIP: {
    open: false,
    title: '会员选择'
  },
  businessType: userStore.userInfo.businessSector
    ? userStore.userInfo.businessSector.split(',')
    : [], //人员所属业务板块信息 businessSector
  hidenDome: [], //隐藏节点
  formDisabled: false, // 禁用表单
  fieldDisabled: [], // 禁用字段
  fieldHidden: ['合同(订单)编号'], // 隐藏字段
  bpmnStatus: '' //表单标题
})
let {
  formRules,
  uploadLoading,
  activeNames,
  crudOptionProduct,
  crudOptionBusiness,
  crudOptionEducation,
  crudOptionRepayment,
  countCrudData,
  repaymentStatisticsData,
  dialogData,
  showTrainingIndustry,
  userOption,
  customerOption,
  dialogParam,
  dialogParamA,
  dialogVIP,
  businessType,
  hidenDome,
  formDisabled,
  fieldDisabled,
  fieldHidden,
  bpmnStatus
} = toRefs(data)
// watchEffect(
//   () => {
//     if (product_property.value.length > 0) {
//       product_property.value = product_property.value.filter(
//         e => e.value !== '1'
//       )
//       console.log('product_property.value', product_property.value)
//     }
//   },
//   { flush: 'post' }
// )
onMounted(() => {
  // console.log('product_property==>', product_property)
  // 判断所属业务分类
  showTrainingIndustry.value = computed(() => {
    // console.log('order_business_type=>2', order_business_type.value)
    let value = false
    let business = order_business_type.value.filter(e => {
      return formData.value.businessType == e.value
    })
    try {
      value =
        business[0].parentId == '财税-培训产业' ||
        business[0].value == '财税-培训产业' ||
        business[0].value == '云财税软件' ||
        business[0].value == '云财税软件运维费'
    } catch (error) {}
    return value
  })
  // 计算产品数据
  countCrudData.value = computed(() => {
    let obj = {
      num: 0,
      total: 0,
      totalDiscountPrice: 0,
      discount: 0,
      totalPrice: 0
    }
    if (
      formData.value.productInfoList &&
      formData.value.productInfoList.length > 0
    ) {
      formData.value.productInfoList.forEach(item => {
        obj.total = Number(item.num) + Number(obj.total)
        obj.totalDiscountPrice =
          Number(item.price) * Number(item.num) + Number(obj.totalDiscountPrice)
        obj.totalPrice = myToFixed(
          Number(item.totalPrice) + Number(obj.totalPrice),
          6
        )
        obj.discount = myToFixed(
          (1 - Number(obj.totalPrice) / Number(obj.totalDiscountPrice)) * 100,
          6
        )
        //  产品总数：countCrudData.total
        //  产品总售价：countCrudData.totalDiscountPrice
        //  整单折扣：countCrudData.discount
        //  产品总金额： countCrudData.totalPrice
      })
      obj.num = formData.value.productInfoList.length
    }
    formData.value.price = Number(obj.totalPrice)
    // console.log('产品金额==》', formData.value.price)
    return obj
  })

  // 计算回款数据
  repaymentStatisticsData.value = computed(() => {
    let obj = {
      num: 0,
      proportion: 0,
      totalPrice: 0
    }
    if (
      formData.value.repaymentPlanList &&
      formData.value.repaymentPlanList.length > 0
    ) {
      formData.value.repaymentPlanList.forEach(item => {
        obj.proportion = Number(item.proportion) + Number(obj.proportion)
        obj.totalPrice = Number(item.price) + Number(obj.totalPrice)
        //         回款占比.proportion
        //         回款金额 totalPrice
      })
      obj.num = formData.value.repaymentPlanList.length
    }
    return obj
  })
})
// watch(
//   () => formData.value.customerId,
//   async (newVal, oldVal) => {
//     console.log(formData.value.customerType, 'formData.value.customerType--')
//     switch (formData.value.customerType) {
//       case 'customer':
//         changeCustomer(formData.value.customerId)
//         break
//       case 'cusLink':
//         // console.log('个人')
//         formData.value.projectId = ''
//         projectOptionsLimitEnt.value = []
//         formData.value.contractIds = []
//         formData.value.contractName = ''
//         contractOptionsLimitEnt.value = []
//         formData.value.cusLinkId = formData.value.customerId
//         formData.value.cusLinkName = formData.value.customerName
//         await queryContactsLimitEnt(
//           formData.value.customerName,
//           '',
//           '',
//           formData.value.customerId
//         )
//         // console.log('newVal,oldVal==>', newVal, oldVal)
//         changeLinkName(formData.value.customerId)
//         // 联系电话赋值
//         // if (resData.bizCustomerAddDto.mainContactPhone) {
//         //   formData.value.linkPhone = resData.bizCustomerAddDto.mainContactPhone
//         // }
//         /**gao start */
//         // 开票抬头赋值
//         formData.value.invoiceTitle = formData.value.customerName
//         // 社会信用代码赋值
//         formData.value.socialCreditCode = formData.value.customerCreditCode
//         // 发票接收人手机赋值
//         formData.value.invoicePhone = ''
//         // 发票接收人手机赋值
//         formData.value.receiveEmail = ''
//         // 企业地址赋值
//         formData.value.invoicePlace = ''
//         // 开户银行赋值
//         formData.value.invoiceBank = ''
//         // 银行账号赋值
//         formData.value.invoiceBankAccount = ''
//         // 所属税局赋值
//         formData.value.taxdeptCode = ''
//         /**gao end */
//         break
//     }
//   },
//   { deep: true }
// )
watch(
  [() => formData.value.customerId, () => formData.value.businessType],
  async () => {
    if (
      showTrainingIndustry.value &&
      industry[formData.value.businessType] &&
      formData.value[`${industry[formData.value.businessType].field}List`]
        .length == 0 &&
      formData.value.customerType == 'cusLink'
    ) {
      let cusLink = contactsOptionsLimitEnt.value.filter(item => {
        return item.id == formData.value.customerId
      })
      let { contactName, contactNumber, idNumber } = cusLink[0]
      formData.value[`${industry[formData.value.businessType].field}List`][0] =
        {
          contactName: contactName,
          contactNumber: contactNumber,
          idNumber: idNumber,
          invoiceTitle: contactName,
          $cellEdit: true
        }
    }
  },
  { deep: true }
)
watch(
  [
    () => route.query.salesOrderId,
    () => route.query.salesOrderData,
    () => props.salesOrderId,
    () => props.id
  ],
  async val => {
    if (route.query.salesOrderId && route.name == type.name) {
      getFormData(route.query.salesOrderId)
    } else if (route.query.salesOrderData && route.name == type.name) {
      let salesOrderData = JSON.parse(route.query.salesOrderData)
      // 管理项目赋值
      if (salesOrderData.projectId) {
        formData.value.projectId = salesOrderData.projectId
        formData.value.projectName = salesOrderData.proName
        projectOptionsLimitEnt.value = [
          {
            projectId: salesOrderData.projectId,
            proName: salesOrderData.proName
          }
        ]
      }
      // 客户类型赋值
      if (salesOrderData.customerType) {
        formData.value.customerType = salesOrderData.customerType
      }
      // 客户名称赋值
      if (salesOrderData.customerId) {
        formData.value.customerId = salesOrderData.customerId
        formData.value.customerName = salesOrderData.customerName
        // changeCustomer(formData.value.customerId)
        customerOption.value['customerId'] = [
          {
            id: salesOrderData.customerId,
            label: salesOrderData.customerName
          }
        ]
      }
    } else if (props.salesOrderId && route.name == 'EditSalesOrder') {
      await getFormData(props.salesOrderId)
      //根据业务查询审批状态
      await getBusinessProStatusFn()
      // 判断表单是否可编辑  获取当前流程节点
      let res = await getNodeData(props.salesOrderId)
      bpmnStatus.value = res.data?.nowTaskName
      formDisabled.value =
        res.data == null || res.data?.isFirst == 'Y' ? false : true

      // 完结后订单未同步的商务可编辑
      let isPurview = userStore.roles //权限信息
      if (
        formData.value.synchronousStatus != '2' &&
        processStatus.value == '05' &&
        isPurview.includes('swgl')
      ) {
        formDisabled.value = false
        fieldHidden.value = []
      }
    } else if (props.id && route.name == 'WorkDetail') {
      await getFormData(props.id)
      // 获取流程节点数据
      if (route.query.processed) {
        // fieldDisabled.value
        let res = await getNodeData(props.id)
        if (res.code !== 200) return
        bpmnStatus.value = res.data?.nowTaskName
        //   res.data == null || res.data?.isFirst == 'Y' ? false : true
        try {
          formDisabled.value = res.data?.formDisabled
        } catch (error) {}
        try {
          let resDis = res.data?.fieldDisabled
          fieldDisabled.value = resDis
            ? resDis.replaceAll(',', '，').split('，')
            : []
          // fieldDisabled.value = ['合同(订单)编号']
        } catch (error) {}
        try {
          let resHid = res.data?.fieldHidden
          fieldHidden.value = resHid
            ? resHid.replaceAll(',', '，').split('，')
            : []
        } catch (error) {}
      }
      formDisabled.value =
        !formDisabled.value && route.query.processed == 'true' ? false : true
      isCanStart.value = false
    } else if (route.name == type.name) {
      if (!formData.value.customerId) {
        selectCustomerFn('customerId')
      }
      isExamine.value = true
      // 走业务流程
      initFlowFn('14')
    }
  },
  {
    immediate: true
  }
)
watch(
  () => formData.value,
  () => {
    if (formData.value.customerName) {
      nextTick(() => {
        proxy.$refs.form.clearValidate(['customerName'])
      })
    }
  },
  {
    deep: true,
    immediate: true
  }
)
// 订单标题赋值
function setTitle() {
  formData.value.title = `${
    formData.value.customerName ? formData.value.customerName : ''
  }${
    formData.value.receiptsDate ? formData.value.receiptsDate : ''
  }的销售订单(${
    formData.value.transactionName ? formData.value.transactionName : ''
  })`
}

// 获取表单信息
async function getFormData(id) {
  proxy.$modal.loading('加载中')
  let res = await getSalesOrder(id)
  if (res.code !== 200) return
  let resData = {}
  resData = res.data
  // 客户数据
  resData.customerId
    ? (customerOption.value['customerId'] = [
        {
          label: resData.customerName, //? resData.customerName: resData.customerId,
          id: resData.customerId //? resData.customerId : resData.customerName
        }
      ])
    : ''
  // 收货单位
  if (resData.receiveDept) {
    parentOptions.value = [
      {
        customerName: resData.receiveDeptName, //? resData.customerName: resData.customerId,
        id: resData.receiveDept //? resData.customerId : resData.customerName
      }
    ]
  }
  //项目数据
  resData.projectId
    ? (projectOptionsLimitEnt.value = [
        {
          proName: resData.projectName,
          projectId: resData.projectId
        }
      ])
    : ''
  //合同数据
  if (resData.contractIds) {
    formData.value.contractNames = resData.contractNames
    contractOptionsLimitEnt.value = resData.contractIds.map((e, i) => {
      return {
        rcId: e,
        contractName: resData.contractNames[i]
      }
    })
  }
  // 联系人数据
  if (resData.cusLinkId) {
    let arr = contactsOptionsLimitEnt.value.filter(
      e => e.id == resData.cusLinkId
    )
    if (arr.length == 0) {
      contactsOptionsLimitEnt.value.push({
        contactName: resData.cusLinkName,
        id: resData.cusLinkId
      })
    }
  }
  // 收货人数据
  if (resData.receiveId) {
    let arr = contactsOptionsLimitEnt.value.filter(
      e => e.id == resData.receiveId
    )
    if (arr.length == 0) {
      contactsOptionsLimitEnt.value.push({
        contactName: resData.receiveName,
        id: resData.receiveId
      })
    }
  }
  // 仓库数据
  if (resData.warehouse) {
    whsOptLimitEnt.value = [
      {
        id: resData.warehouse,
        name: resData.warehouseName
      }
    ]
  }

  // 仓库数据/产品行可编辑
  if (resData.productInfoList.length > 0) {
    resData.productInfoList.forEach((e, i) => {
      if (e.id) {
        resData.productInfoList[i].$cellEdit = true
        if (e.warehouse) {
          let contain = []
          contain = whsOptLimitEnt.value.filter(whs => whs.id == e.warehouse)
          contain.length == 0
            ? whsOptLimitEnt.value.push({
                id: e.warehouse,
                name: e.warehouseName
              })
            : ''
        }
      }
    })
  }

  // 培训产业可编辑
  if (
    industry[resData.businessType] &&
    resData[`${industry[resData.businessType].field}List`].length > 0
  ) {
    resData[`${industry[resData.businessType].field}List`].forEach((e, i) => {
      if (e.id) {
        resData[`${industry[resData.businessType].field}List`][
          i
        ].$cellEdit = true
      }
    })
  }
  // // 继续教育行可编辑
  // if (resData.continuingEducationList.length > 0) {
  //   resData.continuingEducationList.forEach((e, i) => {
  //     if (e.id) {
  //       resData.continuingEducationList[i].$cellEdit = true
  //     }
  //   })
  // }
  // // 会员行可编辑
  // if (resData.memberList.length > 0) {
  //   resData.memberList.forEach((e, i) => {
  //     if (e.id) {
  //       resData.memberList[i].$cellEdit = true
  //     }
  //   })
  // }
  // // 证书行可编辑
  // if (resData.certificateList.length > 0) {
  //   resData.certificateList.forEach((e, i) => {
  //     if (e.id) {
  //       resData.certificateList[i].$cellEdit = true
  //     }
  //   })
  // }
  // // 单课程行可编辑
  // if (resData.courseList.length > 0) {
  //   resData.courseList.forEach((e, i) => {
  //     if (e.id) {
  //       resData.courseList[i].$cellEdit = true
  //     }
  //   })
  // }
  // 回款行可编辑
  if (resData.repaymentPlanList.length > 0) {
    resData.repaymentPlanList.forEach((e, i) => {
      if (e.id) {
        resData.repaymentPlanList[i].$cellEdit = true
      }
    })
  }
  formData.value = resData

  // 默认打开弹窗
  if (route.query.openDialog == 'contract') {
    // 打开合同
    activeDialog()
  }
  // 获取经办人
  if (formData.value.handleId) {
    await getDefaultUserInfo(formData.value.handleId, '_handleId', 'handleId')
  }
  // 获取销售人员
  if (formData.value.transactionId) {
    await getDefaultUserInfo(
      formData.value.transactionId,
      '_transactionId',
      'transactionId'
    )
  }
  proxy.$modal.closeLoading()
}

// 保存/发起流程
async function handleSubmit(type) {
  if (formData.value._handleId) {
    formData.value.handleId = getPricipalId(
      userOption.value['handleId'],
      formData.value._handleId
    ).toString()
  }
  if (formData.value._transactionId) {
    formData.value.transactionId = getPricipalId(
      userOption.value['transactionId'],
      formData.value._transactionId
    ).toString()
  }
  return new Promise((resolve, reject) => {
    // 子表校验
    let subtableCheck = true
    let errMsg = []
    proxy.$refs.form.validate(async (valid, msg) => {
      // 产品信息信息校验
      let err = await proxy.$refs.crudProduct.validateCellForm()
      if (err) {
        // Object.keys(err).forEach(e => {
        //   ;`产品信息---${
        //     induEerrrr[e][0].message
        //   }`
        // })
        errMsg.push(`产品信息---${err[Object.keys(err)[0]][0].message}`)
      }
      subtableCheck = subtableCheck ? !err : subtableCheck

      // 校验订单金额以及订单属性匹配性
      if (
        (formData.value.property == '0' && formData.value.price < 0) ||
        (formData.value.property == '1' && formData.value.price > 0)
      ) {
        subtableCheck = subtableCheck ? false : subtableCheck
        errMsg.push('订单属性与订单金额不匹配')
      }
      // 校验产品的服务时间
      if (formData.value.productInfoList.length > 0) {
        formData.value.productInfoList.forEach(e => {
          if (e.serviceDateRequired == '1' && !e.serviceDateArr[0]) {
            subtableCheck = subtableCheck ? false : subtableCheck
            errMsg.push(`产品信息-${e.name} 服务时间为必填`)
          }
        })
      }

      // 培训产业信息校验
      if (showTrainingIndustry.value && industry[formData.value.businessType]) {
        let induErr = await proxy.$refs[
          industry[formData.value.businessType].field
        ].validateCellForm()
        if (induErr) {
          // Object.keys(induErr).forEach(e => {
          //   ;`${industry[formData.value.businessType].name}---${
          //     induErr[e][0].message
          //   }`
          // })
          errMsg.push(
            `${industry[formData.value.businessType].name}---${
              induErr[Object.keys(induErr)[0]][0].message
            }`
          )
        }
        subtableCheck = subtableCheck ? !induErr : subtableCheck
      }
      if (msg) errMsg.unshift(`${msg[Object.keys(msg)[0]][0].message}`)
      // console.log('msg==>', msg)
      if (valid && subtableCheck) {
        if (type == 'examine') {
          await invoiceDia(type)
        } else {
          try {
            let res = await saveForm(type)
            resolve(res)
          } catch (error) {
            reject(error)
          }
        }
      } else {
        if (errMsg.length > 0) proxy.$modal.msgError(errMsg[0])
        skipToError()
      }
    })
  })
}
//保存客户
async function customerSubmit() {
  if (formData.value.customerId) {
    return
  } else {
    let data = {
      bizCustomerAddDto: {
        origin: '9', //客户来源 (默认）
        customerType: '3', //客户类型 (默认）
        starRating: 0, //客户星级 (默认）
        orgId: userStore.user.orgId, //登录人的orgid (自取)
        userId: userStore.user.userId, //登录人userid （自取）
        customerName: formData.value.customerName, //客户名称 （表单）
        mainContactName: formData.value.cusLinkName, //首要联系人姓名 （表单）
        mainContactPhone: formData.value.linkPhone, //首要联系人手机 （表单）
        deptId: userStore.user.deptId, //登录人deptId （自取）
        userName: userStore.user.userName, //登录人姓名 （表单）
        customerTaxcode: formData.value.customerCreditCode //客户税号
      },
      bizCustomerExtDto: {},
      bizContactDto: {
        sex: '2', //联系人性别 (默认）
        orgId: userStore.user.orgId, //登录人的orgid （自取）
        userId: userStore.user.userId, //登录人userid（自取）
        deptId: 63005, //登录人deptId（自取）
        userName: userStore.user.userName, //登录人姓名 （自取）
        entType: '1', //企业类型 (默认）
        isChiefly: '1' // (默认）
      },
      bizCustomerInvinfoDto: {
        invoiceType: '6', //发票类型 (默认）
        headerType: '1', //发票抬头 (默认）
        invContentType: '1' //发票内容 (默认）
      },
      bizContactExtDto: {}
    }
    console.log('添加新客户', data)
    let res = await createCustomer(data)
    formData.value.customerId = res.data
    let resLink = await getCustomerInfo(formData.value.customerId)
    formData.value.cusLinkId = resLink.data.vo.id
    // formData.value.cusLinkName = resLink.data.vo.id
  }
}

// 保存表单
async function saveForm(type) {
  await customerSubmit()
  return new Promise((resolve, reject) => {
    setSalesOrder(formData.value)
      .then(async res => {
        if (res.code !== 200) {
          reject(res)
          return
        }
        resolve(res)
        await getFormData(res.data.id)
        // 审批流程id赋值
        examineParam.value.businessId = res.data.id
        // console.log('type--', type)
        if (type == 'examine') {
          // 判断是否直接过流程
          let res01 = await orderGoFinish({ orderId: res.data.id })
          if (res01.code != 200) return
          if (res01.data == 'Y') {
            handleExamine()
          } else if (res01.data == 'N') {
            proxy.$modal.msgSuccess('提交成功!该订单自动审批完成!')
            handleReturn()
          }
        } else if (type == 'save') {
          proxy.useReturn(
            '',
            () => {
              //返回上一步
              handleReturn()
            },
            async () => {
              //继续
            }
          )
        }
      })
      .catch(err => {
        reject(err)
      })
  })
}

// 流程同意调用的方法
async function handleSave() {
  if (!formDisabled.value) {
    return await handleSubmit()
  }
}
function handleReset() {
  proxy.resetForm('form')
}

// 显示发票弹出框
const showInvoice = ref(false)
const confirmInvoice = ref(false)
const saveType = ref('')
const invoiceDia = type => {
  showInvoice.value = true
  confirmInvoice.value = false
  saveType.value = type
}
// 确认发票信息
const saveInvoice = async () => {
  proxy.$refs.form.validate(async (valid, msg) => {
    if (valid) {
      if (
        formData.value.invoiceTitle !== formData.value.customerName ||
        formData.value.socialCreditCode !== formData.value.customerCreditCode
      ) {
        await proxy.$modal.confirm(
          '当前开票抬头信息与客户信息不一致，是否确定提交？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        showInvoice.value = false
        confirmInvoice.value = true
        saveForm(saveType.value)
      } else {
        showInvoice.value = false
        confirmInvoice.value = true
        saveForm(saveType.value)
      }
    }
  })
}

/***************************业务流程 模块 start****************************************************************/
/*****审批模块  start*** */
/**
 * 提交审批 按钮
  发布需要的参数 examineParam 参数说明
  visible弹出框是否显示
  businessId //业务id
  businessName//业务名称（如：项目模块 businessName：项目名称）
  amount// 流程设计里面设计的条件参数值
  categoryCode //==>流程分类 页面查看 分类编码：项目1，订单2 客户3 	投标4 采购13 销售14
/**
 * 提交审批 按钮
 */
const handleExamine = async () => {
  if (!examineParam.value.businessId) {
    proxy.$modal.msgWarning('请重新发起审批')
    return false
  }
  examineParam.value.businessName = formData.value.title //订单标题
  examineParam.value.amount = formData.value.price //订单金额
  examineParam.value.categoryCode = '14' //分类编码：项目1，订单2 客户3 	投标4
  examineParam.value.visible = true
}
// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      examineParam.value.visible = false
      break
    case 'initiate':
      //审批 发起成功
      isCanStart.value = false
      examineParam.value.visible = false
      handleReturn()
      break
  }
}
/*****审批模块  end*** */
/**
 * 业务流程整体思路：
 * 1.查询该业务是否有流程
 * 2.根据该业务流程来判断
 * * 2.1没有流程-提示不能新建数据
 * 3.点击发起申请【调组件】
 * * 只有一条流程时，下一环节人的显示 -再发起
 * * 多条流程时，选择流程，再选下一环节人的显示 -再发起
 * @param {*} type  业务类型 项目是1 订单业务2 	客户模块业务3 采购13
 */

async function initFlowFn(type) {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({
    pageNum: 1,
    pageSize: 9999,
    category: type
  })
  flowOptions.value = comRes.rows || []
  // 2.根据
  if (JSON.stringify(flowOptions.value) == '[]') {
    //2.1 没有流程-提示不能新建数据
    if (route.name == type.name) {
      // 新建页面
      proxy.$modal.msgError('该业务没有配置流程，请先创建流程')
    } else {
      //编辑页面
      isExamine.value = false
    }
  } else {
    isExamine.value = true
  }
}
// 编辑页面的时候 -》根据业务查询审批状态
async function getBusinessProStatusFn() {
  let statusRes = await getBusinessProStatus({ businessId: formData.value.id })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    isCanStart.value = true
    initFlowFn('14')
  } else {
    isCanStart.value = false
  }
  if (statusRes.data.status) {
    processStatus.value = statusRes.data.status
  } else {
    processStatus.value = ''
  }
  console.log('是否可发起==》', isCanStart.value)
}
/***************************业务流程 模块 end****************************************************************/

// 选择产品属性时改变业务流程
function changeProProperty(val) {
  //产品属性: 劳务1  商品2  备件3
  //业务流程: 普通流程fj01 服务费流程fj02
  console.log('val==>', val)
  if (val == '1') {
    formData.value.processKey = 'fj02'
  } else {
    formData.value.processKey = 'fj01'
  }
}
// 企业客户时的方法
function changeCustomer(val) {
  if (!val) return
  getCustomerEditInfo(val).then(async res => {
    console.log('客户详情==》', res.data)
    let resData = res.data

    // 联系人赋值
    if (resData.bizCustomerAddDto.mainContactId) {
      formData.value.cusLinkId = resData.bizCustomerAddDto.mainContactId
      formData.value.cusLinkName = resData.bizCustomerAddDto.mainContactName

      queryContactsLimitEnt(
        resData.bizCustomerAddDto.mainContactName,
        formData.value.customerId
      )
    }
    // 联系电话赋值
    if (resData.bizCustomerAddDto.mainContactPhone) {
      formData.value.linkPhone = resData.bizCustomerAddDto.mainContactPhone
    }
    // 关联项目赋值
    queryProjectLimitEnt(null, formData.value.customerId)

    // 关联合同赋值
    queryContractLimitEnt(null, formData.value.customerId)

    // 客户社会信用代码/身份证赋值
    if (resData.bizCustomerAddDto.customerTaxcode) {
      formData.value.customerCreditCode =
        resData.bizCustomerAddDto.customerTaxcode
    }
    // 经办部门赋值
    if (!formData.value.handleDept && resData.bizCustomerAddDto.orgId) {
      formData.value.handleDept = resData.bizCustomerAddDto.orgId
    }
    if (resData.bizCustomerAddDto.orgId != userStore.user.orgId) {
      // proxy.$modal.msgWarning('所选的客户非当前登录人的单位')
      proxy.$confirm('所选的客户非当前登录人的单位', '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    }
    // 经办部门赋值
    if (!formData.value.handleDept && resData.bizCustomerAddDto.orgId) {
      formData.value.handleDept = resData.bizCustomerAddDto.orgId
    }
    // 经办人赋值
    if (!formData.value._handleId && resData.bizCustomerAddDto.userId) {
      await getDefaultUserInfo(
        resData.bizCustomerAddDto.userId,
        '_handleId',
        'handleId'
      )
      // formData.value._handleId = resData.bizCustomerAddDto.userId
    }
    // 业务部门赋值
    // if (!formData.value.transactionDept && resData.bizCustomerAddDto.orgId) {
    //   formData.value.transactionDept = resData.bizCustomerAddDto.orgId
    // }
    // // 销售人员赋值
    // if (!formData.value._transactionId && resData.bizCustomerAddDto.userId) {
    //   await getDefaultUserInfo(
    //     resData.bizCustomerAddDto.userId,
    //     '_transactionId',
    //     'transactionId'
    //   )
    //   // formData.value._handleId = resData.bizCustomerAddDto.userId
    // }
    /**gao start */
    // 开票抬头赋值
    formData.value.invoiceTitle =
      resData.bizCustomerInvinfoDto.taxName || formData.value.customerName
    // 社会信用代码赋值
    formData.value.socialCreditCode =
      resData.bizCustomerInvinfoDto.taxCode || formData.value.customerCreditCode
    // 发票接收人手机赋值
    formData.value.invoicePhone = resData.bizCustomerInvinfoDto.receivePhone
      ? resData.bizCustomerInvinfoDto.receivePhone
      : resData.bizCustomerAddDto.mainContactPhone
    // 发票邮箱赋值
    formData.value.receiveEmail = resData.bizCustomerInvinfoDto.receiveEmail
    // 企业地址赋值
    formData.value.taxAddress = resData.bizCustomerInvinfoDto.taxAddress
    // 企业电话赋值
    formData.value.taxPhone = resData.bizCustomerInvinfoDto.taxPhone
    // 开户银行赋值
    formData.value.invoiceBank = resData.bizCustomerInvinfoDto.bank
    // 银行账号赋值
    formData.value.invoiceBankAccount = resData.bizCustomerInvinfoDto.bankNum
    /**gao end */
    // 所属税局赋值
    if (!formData.value.taxdeptCode && resData.bizCustomerAddDto.taxdeptCode) {
      formData.value.taxdeptCode = Number(resData.bizCustomerAddDto.taxdeptCode)
    }
  })
  /* let customerData = customerOption.value['customerId'] .filter(item => {
    return item.id == val
  })
  console.log('customerData==>', customerData[0]) */
}
// 选择联系人时的方法
function changeLinkName(val) {
  let cusLink = contactsOptionsLimitEnt.value.filter(item => {
    return item.id == val
  })
  // console.log('contactsOptionsLimitEnt.value==>', contactsOptionsLimitEnt.value)
  // console.log('formData.value.cusLink==>', formData.value.cusLinkId)
  if (cusLink.length > 0) {
    // 姓名赋值
    formData.value.cusLinkName = cusLink[0].contactName

    // 联系电话赋值
    if (cusLink[0].contactNumber) {
      formData.value.linkPhone = cusLink[0].contactNumber
    }
    // 身份证赋值
    if (formData.value.customerType == 'cusLink') {
      formData.value.customerCreditCode = cusLink[0].idNumber
        ? cusLink[0].idNumber
        : '350187653627286153'
    }
  } else {
    formData.value.cusLinkName = val
  }
  console.log('cusLink==>', cusLink[0])
}
// 选择收货单位时方法
function changeReceiveDept(val) {
  getCustomerEditInfo(val).then(res => {
    console.log('客户详情==》', res.data)
    let resData = res.data
    if (resData.bizCustomerAddDto.mainContactId) {
      formData.value.receiveId = resData.bizCustomerAddDto.mainContactId
      formData.value.receiveName = resData.bizCustomerAddDto.mainContactName

      queryContactsLimitEnt(
        resData.bizCustomerAddDto.mainContactName,
        formData.value.receiveDept
      )
    }
  })
}
// 选择收货人时的方法
function changeReceive(val) {
  let receive = contactsOptionsLimitEnt.value.filter(item => {
    return item.id == val
  })
  formData.value.receiveName = receive[0].contactName
  console.log('receive==>', receive[0])
}

/**
 * 人员选择
 * @param keyName handleId:经办人  transactionId:销售人员
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'handleId':
      dialogParam.value = {}
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择经办人'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = false
      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = [formData.value['_' + keyName]]
      dialogParam.value.dataType = 'person'
      break
    case 'transactionId':
      dialogParam.value = {}
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择销售人员'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = false
      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.apiParams =
        userStore.userInfo.orgId == 484 ? { deptId: 100 } : undefined
      dialogParam.value.defaultCheckedKeys = [formData.value['_' + keyName]]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = async val => {
  switch (val.type) {
    case 'handleId':
      userOption.value.handleId = val.selectData
      formData.value.handleName = val.labelData.toString()
      formData.value._handleId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
    case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionName = val.labelData.toString()
      formData.value._transactionId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      if (formData.value._transactionId) {
        formData.value.transactionId = getPricipalId(
          userOption.value['transactionId'],
          formData.value._transactionId
        ).toString()
      }
      setTitle()
      const transactionInfo = await getUser(formData.value.transactionId) //查询人员信息
      businessType.value = transactionInfo.data.businessSector
        ? transactionInfo.data.businessSector.split(',')
        : []
      // 所属公司赋值
      formData.value.deptId = transactionInfo.data.orgId
      //业务部门赋值
      formData.value.transactionDept = transactionInfo.data.dept.deptId
      break

    /* case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionId = val.defaultCheckedKeys
      break */
  }
}

/**
 * 根据当前用户id转为uuid（id前加u）
 * @param val 输入用户的id
 * @param fieldName 需要赋值的字段
 * @param selectArr 用户的字典
 */
async function getDefaultUserInfo(val, fieldName, selectArr) {
  let userTree = await commonStore.getUseTreeData()
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(userTree, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(userTree, id, 'id', [])
    if (obj.length > 0) {
      userOption.value[selectArr] = obj
      formData.value[fieldName] = obj[0].uuid
    } else {
      formData.value[fieldName] = 'U' + id
      let label = selectArr.replace(/Id/g, 'Name')
      console.log(' formData.value[label]==>', formData.value[label])
      userOption.value[selectArr] = [
        { uuid: formData.value[fieldName], label: formData.value[label] }
      ]
    }
  }
}
/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName, row) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = formData.value.customerType
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.tabShow = true
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      dialogParamA.value.defaultCheckedKeys = formData.value[keyName]
      dialogParamA.value.defaultCheckedLabel = formData.value['customerName']
      dialogParamA.value.dataType = 'person'
      break
    case 'education':
      dialogParamA.value.type = row.$index
      dialogParamA.value.tabVal = 'cusLink'
      dialogParamA.value.tabShow = false
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      // dialogParamA.value.defaultCheckedKeys = row['customerId']
      break
  }
}

// 客户变更时
const changeCustom = async () => {
  console.log(formData.value.customerType, 'formData.value.customerType--')
  switch (formData.value.customerType) {
    case 'customer':
      changeCustomer(formData.value.customerId)
      break
    case 'cusLink':
      // console.log('个人')
      formData.value.projectId = ''
      projectOptionsLimitEnt.value = []
      formData.value.contractIds = []
      formData.value.contractName = ''
      contractOptionsLimitEnt.value = []
      formData.value.cusLinkId = formData.value.customerId
      formData.value.cusLinkName = formData.value.customerName
      await queryContactsLimitEnt(
        formData.value.customerName,
        '',
        '',
        formData.value.customerId
      )
      // console.log('newVal,oldVal==>', newVal, oldVal)
      changeLinkName(formData.value.customerId)
      // 联系电话赋值
      // if (resData.bizCustomerAddDto.mainContactPhone) {
      //   formData.value.linkPhone = resData.bizCustomerAddDto.mainContactPhone
      // }
      /**gao start */
      // 开票抬头赋值
      formData.value.invoiceTitle = formData.value.customerName
      // 社会信用代码赋值
      formData.value.socialCreditCode = formData.value.customerCreditCode
      // 发票接收人手机赋值
      formData.value.invoicePhone = ''
      // 发票接收人手机赋值
      formData.value.receiveEmail = ''
      // 企业地址赋值
      formData.value.invoicePlace = ''
      // 企业电话赋值
      formData.value.taxPhone = ''
      // 开户银行赋值
      formData.value.invoiceBank = ''
      // 银行账号赋值
      formData.value.invoiceBankAccount = ''
      // 所属税局赋值
      formData.value.taxdeptCode = ''
      /**gao end */
      break
  }
}
// 客户选择选择确定
const selectCustomerData = val => {
  if (val.type == 'customerId') {
    customerOption.value.customerId = val.selectData
    formData.value.customerType = val.tabVal
    formData.value.customerName = val.labelData.toString()
    if (formData.value.customerId !== val.defaultCheckedKeys.toString()) {
      setTitle()
      formData.value.projectId = '' //清空项目
      formData.value.projectName = '' //清空项目
      formData.value.contractId = '' //清空合同
      formData.value.contractIds = [] //清空合同
      formData.value.contractNames = [] //清空合同
    }
    formData.value.customerId = val.defaultCheckedKeys
      ? val.defaultCheckedKeys.toString()
      : null
    changeCustom()
  } else if (typeof Number(val.type) == 'number') {
    if (
      formData.value[`${industry[formData.value.businessType].field}List`][
        val.type
      ].contactId !== val.defaultCheckedKeys.toString()
    ) {
      setTitle()
      // 客户名称赋值
      formData.value[`${industry[formData.value.businessType].field}List`][
        val.type
      ].contactName = val.labelData.toString()
      // 发票抬头赋值
      formData.value[`${industry[formData.value.businessType].field}List`][
        val.type
      ].invoiceTitle = val.labelData.toString()
      // 客户税号赋值
      if (val.selectData.length > 0) {
        formData.value[`${industry[formData.value.businessType].field}List`][
          val.type
        ].contactNumber = val.selectData[0].contactNumber
        formData.value[`${industry[formData.value.businessType].field}List`][
          val.type
        ].idNumber = val.selectData[0].idNumber
      } else {
        formData.value[`${industry[formData.value.businessType].field}List`][
          val.type
        ].contactNumber = ''
      }
      // 客户id赋值
      formData.value[`${industry[formData.value.businessType].field}List`][
        val.type
      ].contactId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
    }
  }
}

// 打开vip选择
function openVIP(data, dataType) {
  dialogVIP.value.open = true
  dialogVIP.value.$index = data.$index
  dialogVIP.value.dataType = dataType
  dialogVIP.value.queryParams = { vipType: dataType == '诺账通' ? '2' : '1' }
  // console.log('data==>', data)
}
// 确定vip
function selectVIP(val) {
  if (val.selectData.length < 1) return proxy.$message.error('请选择会员')
  if (val.dataType == '诺账通') {
    formData.value.productInfoList[val.$index].keyValue =
      val.selectData[0].keyValue
    formData.value.productInfoList[val.$index].membershipLevel =
      val.selectData[0].name
    formData.value.productInfoList[val.$index].equityContent = JSON.stringify(
      val.selectData[0]
    )
  } else {
    formData.value[`${industry[formData.value.businessType].field}List`][
      val.$index
    ].keyValue = val.selectData[0].keyValue
    formData.value[`${industry[formData.value.businessType].field}List`][
      val.$index
    ].membershipLevel = val.selectData[0].name
    formData.value[`${industry[formData.value.businessType].field}List`][
      val.$index
    ].equityContent = JSON.stringify(val.selectData[0])
    // console.log('vip==>', val)
  }
  dialogVIP.value.open = false
}
// 添加产品
function addProduct() {
  console.log('dialogData.value.open', dialogData.value.open)
  dialogData.value.open = true
  dialogData.value.productQuery = {
    createUnit: formData.value.deptId, //产品所属单位
    zeroExitControl: '1', //0库存出库
    productFilter: 'y', //过滤所属板块
    businessType: businessType.value //所属板块
  }
  dialogData.value.comboQuery = {
    deptId: formData.value.deptId //套餐所属单位
  }
}
// 确定添加产品
function productDialogFn(val, tabName) {
  // deviceType 设备类型 0专用1非专用
  // proType: '0', //0通用 1专用
  switch (tabName) {
    case 'ProductMange':
      if (val.length == 0) return proxy.$message.error('请选择产品')
      let laborService = val[0].laborService
      let isHaveLabor = val.some(item => {
        return item.laborService != laborService
      })
      let proType = val[0].deviceType
      let isProType = val.some(item => {
        return item.deviceType != proType
      })
      if (isHaveLabor)
        return proxy.$message.error(
          '您选择了两个不同的劳务类型的产品，请选择同一种'
        )
      if (isProType)
        return proxy.$message.error(
          '您选择了两个不同的设备类型的产品，请选择同一种'
        )
      // if (
      //   formData.value.productInfoList.length > 0 &&
      //   proType != formData.value.productInfoList[0]?.deviceType
      // ) {
      //   return proxy.$message.error({
      //     message: '您选择的产品与已有产品的类型不一致，请选择同一种',
      //     duration: 5000
      //   })
      // }
      // 判断劳务服务赋值产品属性
      formData.value.proProperty = formData.value.proProperty
        ? formData.value.proProperty
        : laborService == '1'
        ? '1'
        : '2' //标记劳务服务 劳务1  商品2  备件3'
      // 判断设备类型赋值产品类型
      formData.value.proType = formData.value.proType
        ? formData.value.proType
        : proType == '0'
        ? '1'
        : '0'

      let formlaborService = formData.value.proProperty == '1' ? '1' : '0'
      let formProProperty = val.some(
        item => item.laborService != formlaborService
      )
      if (formProProperty)
        return proxy.$message.error('请选择劳务类型一致的产品')

      let formProType = val.some(item => {
        let deviceType = item.deviceType == '0' ? '1' : '0'
        return deviceType != formData.value.proType
      })
      if (formProType)
        return proxy.$message.error({
          message: '请选择产品类型一致的产品',
          duration: 5000
        })
      val.forEach(e => {
        formData.value.productInfoList.push({
          ...e,
          ...{
            $cellEdit: true,
            num: 1,
            extensionNo: 0,
            // actualPrice: e.price,//实际售价不用自动带进来
            // totalPrice: e.price,//总价不用自动带进来
            productId: e.id,
            discount: 0
          }
        })
      })
      changeProProperty(formData.value.proProperty)
      break
    case 'ComboMange':
      val.forEach(e => {
        e.productInfoList.forEach(item => {
          formData.value.productInfoList.push({
            ...item,
            ...{
              $cellEdit: true,
              extensionNo: 0,
              // actualPrice: item.price,//实际售价不用自动带进来
              //totalPrice: Number(item.price) * Number(item.num),//总价不用自动带进来
              discount: 0
            }
          })
        })
      })
      // 判断劳务服务赋值产品属性
      formData.value.proProperty =
        val[val.length - 1].productInfoList[
          val[val.length - 1].productInfoList.length - 1
        ].laborService == '1'
          ? '1'
          : '2'
      changeProProperty(formData.value.proProperty)
      break
  }
  queryWhsLimitEnt('', { unit: formData.value.deptId })
}
// changeWhs选择仓库时
async function changeWhs(val, row) {
  let params = {
    productId: row.productId,
    warehouseId: val
  }
  let res = await getInventory(params)
  row.inventory = res.data
}
// 删除产品行
function delRowProduct(row, index, done) {
  proxy
    .$confirm('是否删除该产品', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      formData.value.productInfoList.splice(index, 1)
      proxy.$message({
        type: 'success',
        message: '删除成功!'
      })
      if (formData.value.productInfoList.length == 0) {
        formData.value.proProperty = ''
        formData.value.proType = ''
        changeProProperty(formData.value.proProperty)
      }
    })
    .catch(() => {})
}

/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = ['.xls', '.xlsx'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error('上传文件只能是xls、xlsx格式!')
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
async function requestFile(params) {
  uploadLoading.value = true
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  uploadData.append('type', formData.value.businessType)
  try {
    let res = await importData(uploadData)
    uploadLoading.value = false
    if (res.code === 200) {
      proxy.$modal.msgSuccess('导入成功')
      res.data.forEach(e => {
        formData.value[
          `${industry[formData.value.businessType].field}List`
        ].push({
          ...e,
          $cellEdit: true
        })
      })
    }
  } catch (error) {
    uploadLoading.value = false
  }
}
// 切换所属业务分类时
function changeBusinessType(val) {
  /*
    continuingEducationList: [], //培训产业-继续教育列表
    memberList: [], //培训产业-会员列表
    certificateList: [], //培训产业-证书列表
    courseList: [], //培训产业-单课程列表
  */
  if (val == '培训产业-继续教育') {
    formData.value.memberList = []
    formData.value.certificateList = []
    formData.value.courseList = []
  } else if (val == '培训产业-会员') {
    formData.value.continuingEducationList = []
    formData.value.certificateList = []
    formData.value.courseList = []
  } else if (val == '培训产业-证书') {
    formData.value.continuingEducationList = []
    formData.value.memberList = []
    formData.value.courseList = []
  } else if (val == '培训产业-单课程') {
    formData.value.continuingEducationList = []
    formData.value.memberList = []
    formData.value.certificateList = []
  }
}
// 添加培训产业
function addEducation() {
  formData.value[`${industry[formData.value.businessType].field}List`].push({
    $cellEdit: true
  })
  // console.log('product==>', formData.value.repaymentPlanList)
}
// 删除培训产业行
function delEducation(row, index, done) {
  proxy
    .$confirm('是否删除该客户', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      formData.value[
        `${industry[formData.value.businessType].field}List`
      ].splice(index, 1)
      proxy.$message({
        type: 'success',
        message: '删除成功!'
      })
    })
    .catch(() => {})
}

// 添加回款
function addRowRepayment() {
  formData.value.repaymentPlanList.push({ $cellEdit: true, price: 0 })
  // console.log('product==>', formData.value.repaymentPlanList)
}
// 回款计划期次赋值
function rowIndex(row) {
  row.period = row.$index + 1
  return row.$index + 1
}
// 删除回款行
function delRowRepayment(row, index, done) {
  proxy
    .$confirm('是否删除该回款计划', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      if (row.id) {
        delRepaymentPlan(row.id).then(e => {
          formData.value.repaymentPlanList.splice(index, 1)
          proxy.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      } else {
        formData.value.repaymentPlanList.splice(index, 1)
        proxy.$message({
          type: 'success',
          message: '删除成功!'
        })
      }
    })
    .catch(() => {})
}
let selectDept = [] //储藏初始单位
const changeDept = val => {
  let dept = getTreeNodeByParam(companyNoPrivOption.value, val, 'id', [])
  formData.value.deptName = dept[0].label

  if (selectDept[0].id == val) return
  proxy.$modal
    .confirm('改变销售单位产品信息将清空？')
    .then(() => {
      formData.value.productInfoList = []
    })
    .catch(() => {
      formData.value.deptId = selectDept[0].id
    })
}
//储藏初始单位
const focusDept = event => {
  const value = event.target.value
  let dept = getTreeNodeByParam(companyNoPrivOption.value, value, 'label', [])
  selectDept = dept
}
/****    关联合同开始++++++++++++++++++++++++++++    ***/
const paramsContract = ref({
  visible: false,
  businessId: '',
  businessName: '客户名称'
})

// 确认关联合同
function saveFn(data) {
  // console.log('合同data', data.selectData)
  const ids = data.selectData.map(v => v.rcId) || []
  formData.value.contractIds = ids
  formData.value.contractNames = data.selectData.map(v => v.contractName)
  formData.value.contractRemark = data.formData.contractRemark
}

// 打开弹窗
function activeDialog() {
  const id = formData.value.customerId
  if (!id) {
    proxy.$modal.msgError('请先选择客户名称')
    return
  }
  if (
    formData.value.businessType.indexOf('代理记账') != '-1' &&
    (!formData.value.contractSum ||
      !formData.value.contractTimeBegin ||
      !formData.value.contractTimeEnd)
  ) {
    proxy.$modal.msgError('请先输入合同金额、合同时间起、合同时间止')
    return
  }
  const ids = formData.value.contractIds
  /***订单模块 */
  paramsContract.value.open = true
  paramsContract.value.multiple = true // 是否多选
  paramsContract.value.title = formData.value.customerName //名称 -- 显示dialog title
  paramsContract.value.queryParams = {
    partya: formData.value.customerId, // 根据客户id查询合同列表
    uploadType: '1'
  }
  paramsContract.value.initData = {
    customerName: formData.value.customerName, //甲方签约人
    customerId: formData.value.customerId, //合同甲方
    deptName: formData.value.deptName, //乙方签约人
    deptId: formData.value.deptId, //合同乙方
    title: formData.value.title, //props.dialogParam.initData.title, //合同名称
    receiptsDate: formData.value.receiptsDate, //签订时间
    contractSum: formData.value.contractSum, //合同金额
    contractTimeBegin: formData.value.contractTimeBegin, //合同时间起
    contractTimeEnd: formData.value.contractTimeEnd, //合同时间止
    businessType: formData.value.businessType, //业务属性
    uploadType: formData.value.businessType,

    contractList:
      formData.value.contractIds && formData.value.contractIds.length > 0
        ? formData.value.contractIds.map((e, i) => {
            return {
              rcId: e,
              contractName: formData.value.contractNames[i]
            }
          })
        : []
  }
  // params.value = {
  //   visible: true, // 显示dialog
  //   businessId: id, // 根据id查询合同列表
  //   businessName: customerOption.value['customerId'][0].label, // 名称 -- 显示dialog title
  //   multiple: true, // 是否多选
  //   defaultSelect: ids ? ids : [], // 默认选择数据
  //   uploadType: '1'
  // }
}

// 弹窗确认完成回调
function relatedOver(val) {
  console.log('nnn', val)
  const ids = val.map(v => v.rcId) || []
  formData.value.contractIds = ids
  formData.value.contractNames = val.map(v => v.contractName)
}

// el-input clear函数
function clearAll() {
  formData.value.contractId = ''
  formData.value.contractName = ''
  formData.value.contractIds = []
  formData.value.contractNames = []
}

// 上传合同
const isUpdateConstract = ref(false) // 是否更新合同信息
function uploadConstarct() {
  showUpload.value = true
  isUpdateConstract.value = false
}

const selected = ref()
const constractParams = ref({})
// 更新合同方法
function editContract(val) {
  if (val.uploadType) {
    selected.value = val
    proxy.$modal
      .confirm('当前操作将前往更新合同的附件信息，是否继续操作')
      .then(() => {
        // 调用详情接口获取附件信息
        contractDetails(val.rcId)
          .then(res => {
            console.log(res)
            if (res.data) {
              fileList.value = res.data.sysAttachFiles || []
            }
          })
          .finally(() => {
            // 更新合同参数
            isUpdateConstract.value = true
            showUpload.value = true
          })
      })
  } else {
    selected.value = null
  }
}

const showInput = ref(false) // 编辑页面直接显示备注信息
const showUpload = ref(false)
const fileList = ref([]) // 文件列表
// 上传前检查文件类型大小
function beforeUpload(rawFile) {
  const type = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = ['.rar', '.zip', '.doc', '.docx', '.pdf'].indexOf(type) < 0
  if (allowType) {
    proxy.$message.error('上传文件只能是rar、zip、doc、docx、pdf格式!')
    return
  }
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}

// 上传方法
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    } else {
      console.log(res.msg)
    }
  } catch (error) {
    console.error(error)
  }
}

// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    console.log(error)
  }
}

// 取消上传
function cancelUpload() {
  showUpload.value = false
}

// 确认上传
const relatedContract = ref()
function finishedUpload() {
  if (fileList.value.length <= 0) {
    cancelUpload()
    return
  }
  constractParams.value.partyaSig = customerOption.value['customerId'][0].label // 签约人甲方
  constractParams.value.partya = formData.value.customerId
  constractParams.value.partyaName = constractParams.value.partyaSig
  constractParams.value.partybSig = companyOption.value[0].children.find(
    v => v.id === formData.value.deptId
  ).label // 签约人乙方
  constractParams.value.partyb = formData.value.deptId
  constractParams.value.partybName = constractParams.value.partybSig
  constractParams.value.contractName = formData.value.title //合同名称
  constractParams.value.contractAttribute = '1' // 合同类别
  constractParams.value.uploadType = 1 // 订单添加合同标志位
  // constractParams.value.contractNum = '0000' // 合同编号
  // constractParams.value.contractSum = formData.value.price //合同金额
  constractParams.value.businessType = '0' // 合同类别
  constractParams.value.sinTime = formData.value.receiptsDate // 合同签约时间
  // constractParams.value.businessCategorize = formData.value.businessType //  所属业务分类
  constractParams.value.pbAlonePay = '2'
  constractParams.value.sysAttachFiles = fileList.value
  constractParams.value.fileNames = fileList.value.map(v => v.fileName)
  if (isUpdateConstract.value) {
    constractParams.value.rcId = selected.value.rcId
    contractInfoUpdate(constractParams.value).then(res => {
      proxy.$refs.relatedContract.getList()
      fileList.value = []
      cancelUpload()
    })
  } else {
    contractInfoSave(constractParams.value).then(res => {
      proxy.$refs.relatedContract.getList()
      fileList.value = []
      cancelUpload()
    })
  }
}
/****    ++++++++++++++++++++++++++++    ***/

/****    关联项目  开始  ***/
const proParams = ref({
  visible: false,
  businessId: '',
  businessName: '客户名称'
})
// 打开弹窗
function selectPro() {
  const id = formData.value.customerId
  if (!id) {
    proxy.$modal.msgError('请先选择客户名称')
    return false
  }
  const ids = formData.value.projectId
  proParams.value = {
    visible: true, // 显示dialog
    businessId: id, //客户id
    businessName: formData.value.customerName, //客户名称
    multiple: false, // 是否多选
    defaultSelect: ids ? ids : [] // 默认选择数据
  }
  // 注意： 如果不需要选客户名称的话，这个businessId，businessName 可以不传
}

// 弹窗确认完成回调
function relatedPro(val) {
  if (val) {
    const name = proParams.value.multiple
      ? val.map(v => v.proName).toString() || ''
      : val.proName

    const ids = proParams.value.multiple
      ? val.map(v => v.projectId) || []
      : val.projectId

    formData.value.projectId = ids
    formData.value.projectName = proParams.value.multiple
      ? val.map(v => v.proName)
      : name
    console.log(formData.value.projectName, ' formData.value.projectName')
  }
  closePro()
}

// 关闭弹窗
function closePro() {
  proParams.value.visible = false
}

// el-input clear函数
function clearPro() {
  formData.value.projectId = null
  formData.value.projectName = null
}
/****    关联项目  end   ***/

/*** +++++++++++++++++++++++++   关联订单   +++++++++++++++++++++++++***/
const redOrderId = ref() //用于关联发票查询
const orderParams = ref({})
// 打开弹窗
function activeOrdDialog() {
  const id = formData.value.customerId
  if (!id) {
    proxy.$modal.msgError('请先选择客户')
    return false
  }
  orderParams.value = {
    visible: true, // 显示dialog
    businessId: id, // 根据客户id查询合同列表
    // businessName: formData.value.customerName,
    multiple: false, // 是否多选
    otherParameters: {
      property: '0'
    }
    // defaultSelect: formData.value.oppositeId ? formData.value.oppositeId : [] // 默认选择数据
  }
}

async function ordRelatedOver(val) {
  console.log(val, 'order')
  if (val) {
    const name = orderParams.value.multiple
      ? val
          .map(v => {
            return v.contractOrderNumber
              ? `${v.contractOrderNumber}-${v.orderTitle}`
              : `${v.orderTitle}`
          })
          .toString() || ''
      : val.contractOrderNumber
      ? `${val.contractOrderNumber}-${val.orderTitle}`
      : val.orderTitle

    const ids = orderParams.value.multiple
      ? val.map(v => v.orderId) || []
      : val.orderId

    formData.value.oppositeId = ids
    formData.value.oppositeName = name
    formData.value.correspondingInvoiceNumber = ''
    const res = await getSalesOrder(val.orderId)
    const {
      invoiceType,
      headerType,
      invoiceTitle,
      socialCreditCode,
      invoicePhone,
      receiveEmail,
      taxPhone,
      invoicePlace,
      invoiceBank,
      invoiceBankAccount,
      productInfoList,
      proProperty,
      processKey,
      contractNames,
      contractIds,
      projectName,
      projectId,
      id
    } = res.data
    redOrderId.value = id
    formData.value.proProperty = proProperty
    formData.value.processKey = processKey
    formData.value.invoiceType = invoiceType
    formData.value.headerType = headerType
    formData.value.invoiceTitle = invoiceTitle
    formData.value.socialCreditCode = socialCreditCode
    formData.value.invoicePhone = invoicePhone
    formData.value.receiveEmail = receiveEmail
    formData.value.taxPhone = taxPhone
    formData.value.invoicePlace = invoicePlace
    formData.value.invoiceBank = invoiceBank
    formData.value.invoiceBankAccount = invoiceBankAccount
    formData.value.contractNames = contractNames
    formData.value.contractIds = contractIds
    formData.value.projectName = projectName
    formData.value.projectId = projectId
    formData.value.productInfoList = productInfoList.map(e => {
      return {
        ...e,
        num: e.num * -1,
        totalPrice: e.totalPrice * -1,
        $cellEdit: true
      }
    })
    console.log('蓝单res==>', res)
  }
  ordCloseDialog()
}
/*** +++++++++++++++++++++++++   关联订单结束   +++++++++++++++++++++++++***/
// 关闭弹窗
function ordCloseDialog() {
  orderParams.value.visible = false
}
// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

/* 关联发票开始 */
const redInvoiceParam = ref({
  open: false
})
// 关联发票
async function reversalOrder() {
  if (!redOrderId.value) return proxy.$modal.msgError('请先关联订单')
  redInvoiceParam.value.open = true
  redInvoiceParam.value.isSelection = true
  redInvoiceParam.value.multiple = false
  redInvoiceParam.value.query = {
    orderId: redOrderId.value,
    openStatus: '1'
  }
}
// 关联发票弹窗时
const redDialogFn = val => {
  console.log('开票==>', val)
  formData.value.correspondingInvoiceNumber = val[0].number
  getDetailByNumber({ number: formData.value.correspondingInvoiceNumber }).then(
    res => {
      formData.value.productInfoList = res.data.map(e => {
        return {
          ...e,
          num: e.num * -1,
          totalPrice: e.totalPrice * -1,
          $cellEdit: true
        }
      })
    }
  )
}
/* 关联发票结束 */

// 订单编号赋值给合同订单编号
const getNumber = () => {
  formData.value.contractOrderNumber = formData.value.number
}

// 签购单
const salesSlipDia = ref({
  open: false,
  queryParam: {}
})
const handleSalesSlip = () => {
  salesSlipDia.value = {
    open: true,
    title: '签购单',
    queryParam: {
      orderId: formData.value.id
    }
  }
}

//暴露出保存方法
defineExpose({ handleSave })
</script>
<style scoped>
.salesOrderForm .el-collapse {
  border-top: none;
}
.form-box :deep(.w-full) {
  width: 100%;
}
/* .order-form :deep(.avue-crud__menu) {
  border-bottom: 1px solid #eee;
} */
.form-box:deep(.daterangeClass .el-date-editor--daterange) {
  width: 100%;
}
.form-box:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}

.form-box:deep(.el-input-group__append) {
  padding: 0 12px;
}
:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
